猫鼬发现并保存不工作

时间:2016-07-01 19:57:53

标签: node.js mongodb mongoose save

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

但我要发送的html在" "仍然包含res.send(),即html函数回调后变量User.find()中没有反映出来的变化

有关如何解决此问题的任何想法?

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);

});

1 个答案:

答案 0 :(得分:0)

您的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);
        });
    }
});