【问题标题】:Keeping mongoose functions separately in nodejs app with promises使用 Promise 在 nodejs 应用程序中单独保留 mongoose 函数
【发布时间】:2018-08-11 10:01:55
【问题描述】:

我想单独保留一些猫鼬函数以获得更整洁的代码,我想处理承诺,下面是一个插图。

Model.js 文件

var User = module.exports = mongoose.model('User', UserSchema);

module.exports.createUser = function(newUser, callback){
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback); 
        });
    });
}

这里createUser是自定义函数,我的route.js如下,

router.post('/register', function(req, res){
    var newUser = new User({
        email: req.body.email,
        password: req.body.password
    });

    User.createUser(newUser)
        .then(function(user){
            console.log(user)
            res.redirect('/users/login');
        })
        .catch(function(err){
            console.log(err)
        })

})

使用 promises 这会显示“.then undefined”和“.save() 不是函数”的错误

请纠正我,提前谢谢。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    这不起作用,因为 createUser(..) 不返回 promise。为了使.then() 起作用,它应该被链接到一个返回承诺的函数。

    你必须从createUser()返回一个承诺:

    module.exports.createUser = function(newUser){
        return new Promise((resolve,reject)=>{
            bcrypt.genSalt(10, function(err, salt) {
                bcrypt.hash(newUser.password, salt, function(err, hash) {
                    if(err){reject(err);}// err is passed on to the catch() call
                    newUser.password = hash;
                    resolve(newUser); // newUser is passed on to the then() call chained after the call to createUser()
                });
            });
        })
    }
    

    这应该有效:

    module.exports.createUser = function(newUser){
            return new Promise((resolve,reject)=>{
                bcrypt.genSalt(10, function(err, salt) {
                    bcrypt.hash(newUser.password, salt, function(err, hash) {
                        if(err){reject(err);}// err is passed on to the catch() call
                        newUser.password = hash;
                        newUser.save(function(err, newUser){
                            if(err){return reject(err);}                        
                            resolve(newUser); // newUser is passed on to the then() call chained after the call to createUser()
                        })
                    });
                });
            })
        }
    

    查看promises 了解更多信息。

    希望这会有所帮助!

    【讨论】:

    • 但是我们在哪里运行 .save() ?这样它就保存在猫鼬中
    • 它成功了,谢谢,但是你知道保存在哪里吗??
    • 在 .then() 中运行它。
    • 所以不能在model.js文件的createUser函数中运行
    • 如果出错你应该“return reject(err)”,没有return语句,用户仍然会被插入到mongo中(至少会执行)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 2016-10-18
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多