链接承诺与mongoose(mPromises)

我正在寻找如何链接使用nodejs / mongoose(mPromise)“fin或创build”function的承诺,

我目前尝试过:

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:对象#没有方法“链”。

我使用这个:

-mongoose@3.8.17

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

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

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

谢谢。