用猫鼬链接承诺(mPromises)

时间:2015-01-08 17:24:16

标签: node.js validation mongoose promise chain

我正在寻找有关如何使用nodejs / mongoose(mPromise)链接“fin或create”功能的承诺的建议

我目前正在尝试:

var findExistingUsername = function(value){
	console.log('existusername');
 	return mongoose.models["User"].findOne({username: value})
  	.lean()
  	.exec();
};

var findExistingEmail= function(value){
	console.log('existusername');
 	return mongoose.models["User"].findOne({email: value})
  	.lean()
  	.exec();
};

var validateEmail = function(value){
	console.log('existusername');
 	var emailRegex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    console.log('Email valido?:' + emailRegex.test(email));
    return emailRegex.test(email);
};

var addUser = function(data){
	console.log('existusername');
 	return mongoose.models["User"].create(data);
};


UserSchema.methods = {

validateAndAddUser: function(req, res) {

	return findExistingUsername(this.username)
			.then(function(existingUser){
				if(existingUser)
					throw 'El nombre de usuario ya está cogido.'
			})
			.chain(findExistingEmail(this.email))
			.then(function(existingEmail){
				if(existingEmail)
					throw 'El correo electrónico ya está registrado.'
			})
			.chain(addUser(this))
			.then(function(){
		    	console.log('user creado con exito.');			    	
		    })
		    .onResolve(function(){
		    	console.log('success');
		    	res.status(200).json({
			            payload: 'user',
			            message: "Cuenta creada con éxito"});
		    })
		    .onReject(function(err){
		    	console.log('err');
		    	res.status(400).json({
			          payload: err.code,
			          message: err});
		    });
}};

从我的(node / express)API端点调用它:

exports.createUser = function (req, res) {
    var newUser = new UserModel(req.body);
	// Promise
	newUser.validateAndAddUser(req, res).fulfill();
};

问题:

1)我不确定我是否使用了正确的承诺风格/最有效的编码风格。

2)TypeError:Object#没有方法'chain'。

我正在使用这个:

-mongoose@3.8.17

- https://github.com/aheckmann/mpromise

- https://nadeesha.silvrback.com/a-quick-intro-to-mpromise-in-mongoose

任何人都可以看到我做错了什么,以及我怎样才能做得更好?

感谢。

0 个答案:

没有答案
相关问题