Node.js 如何使用蓝鸟处理猫鼬的承诺返还?

Node.js 如何使用蓝鸟处理猫鼬的承诺返还?,node.js,mongoose,bluebird,Node.js,Mongoose,Bluebird,我有一个账户模式,用猫鼬定义,我用蓝鸟设定了承诺: var mongoose = require('mongoose'); mongoose.Promise = require('bluebird'); 我为这种模式设计了一种模型方法: accountSchema.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.password); } 因此,我找到了一种方法,

我有一个
账户
模式,用猫鼬定义,我用蓝鸟设定了承诺:

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
我为这种模式设计了一种模型方法:

accountSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.password);
}
因此,我找到了一种方法,该方法将尝试查找用户并检查密码匹配情况:

function login (email,password) {

    return Account.findOne({email: email}).then(function (user) {
        console.log(user);
        user["match"] = user.validPassword(password);
        console.log(user);
        return user.validPassword(password);
    });
}
真正奇怪的是,第二个
控制台.log
不会显示对象的任何
匹配属性。

在这里,我的意图是返回一个承诺,即找到一个用户并检查密码是否匹配,但是当我调用login时:

login("email","password").then(function(user){...})
用户没有匹配属性,我如何实现它?

登录(电子邮件、密码){
返回新承诺(功能(解决、拒绝){
Account.findOne({email:email}).then(函数(用户){
user.match=user.validPassword(密码);
解析(用户)
});
})

}
在调用承诺调用之前,不能同时执行返回操作:return Account.xxxxx和执行.then()。。。。这是一个非此即彼的问题。。。我给你两种选择。版本A我们将resultset本地处理为登录函数:

function login (email,password) {

    // notice I no longer have return Account.xxxx
    Account.findOne({email: email}) // Account.findOne returns a Promise
    .then(function (user) {

        if (user) {

            user.match = user.validPassword(password);
            // execute some callback here or return new Promise for follow-on logic

        } else {
            // document not found deal with this
        }

    }).catch(function(err) {

        // handle error
    });
}
在这里,调用方执行以下操作:

login("email","password") // needs either a cb or promise
.then(function(userProcessed) { ... 
}).
。。。而在版本B中,我们将处理降级到调用方来执行.then()逻辑:

因此,我们有:

login("email","password").then(function(userNotProcessed){...})
findOne
获得结果集后,请对
用户执行一些验证,避免假设已找到该结果集。
另外,由于Promise现在位于ES6中,因此可以使用内置的Promise实现

mongoose.Promise = global.Promise;

请注意,
findOne
返回一个文档,而执行
find
总是会给您一个包含0个或多个文档的数组

这正是我要做的。我需要在控制器上使用login函数,所以它确实需要返回一些东西,这就是我试图返回承诺的原因。即使是最后一次编辑,你的答案还是一样的,我已经在做了。在他添加了清晰的回报后,我同意@DiegoaGuillar如果您当时正在调用FindOne,则不希望在FindOne调用之前返回。值得注意的是,在上面的示例中,login是一个可设置的函数。从“then”内部返回的一切都是一个新的承诺。diegoaguilar,这应该是有效的。不想要的结果是什么?这是包装在登录函数中的,对吗?
mongoose.Promise = global.Promise;