【问题标题】:Mongoose find and save not working猫鼬查找并保存不起作用
【发布时间】:2016-11-04 07:41:19
【问题描述】:

我正在尝试使用 Mongoose 在数据库中查找特定用户,并根据是否存在相同的数据来保存或忽略数据。

但我要发送的html在res.send()处仍然包含" ",也就是说,User.find()函数回调后变量html没有反映任何变化。

关于如何解决这个问题的任何想法?

var html = "";
app.post('/', function(req, res){

    var name_of_user = req.body.username;
    var userObject = new User({
        username: req.body.username,
        email : req.body.email,
        password : req.body.password
    });

    User.find({"username" : name_of_user}, function(err,docs) {
        if(docs.length) {
            console.log('Name exists already');
            html = '<i>' + userObject.username + '</i> is already a registered user!';
            html += '<br><br><br><a href="http://localhost:3000/">Try again</a>';
        }
        else {
            userObject.save(function(err, user) {
                if (err) return console.error(err);
            });
            html = 'Successfully signed up as <i>' + name_of_user +
                '</i>. Added <i>' + name_of_user + '</i> to the MongoDB database.';
            html += '<br><br><br><a href="http://localhost:3000/">Go back</a>';
        }

        //console.log(docs);
    });

    res.send(html);

});

【问题讨论】:

  • 我的回答解决了你的问题吗?

标签: node.js mongodb mongoose save


【解决方案1】:

你的res.send(html) 在回调之外,所以它在回调之前被调用。您必须将该调用移动到回调中才能依赖它们的结果。

User.find({"username" : name_of_user}, function(err,docs) {
    if(docs.length) {
        console.log('Name exists already');
        html = '<i>' + userObject.username + '</i> is already a registered user!';
        html += '<br><br><br><a href="http://localhost:3000/">Try again</a>';
        res.send(html);
    }
    else {
        userObject.save(function(err, user) {
            if (err) return console.error(err);

            html = 'Successfully signed up as <i>' + name_of_user +
                   '</i>. Added <i>' + name_of_user + '</i> to the MongoDB database.';
            html += '<br><br><br><a href="http://localhost:3000/">Go back</a>';
            res.send(html);
        });
    }
});

【讨论】:

    猜你喜欢
    • 2015-11-16
    • 2017-10-05
    • 1970-01-01
    • 2021-03-10
    • 2017-03-08
    • 2018-04-10
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    相关资源
    最近更新 更多