【问题标题】:Can't update the mongodb document on the fly无法即时更新 mongodb 文档
【发布时间】:2015-02-21 13:44:15
【问题描述】:

我对 Node.js 和 MongoDB 还是很陌生。我正在尝试使用此代码,其中我有一个名为 test 的布尔文档,该文档在 Mongodb 中最初为“假”,我想在加载页面 /hello 时提醒这一点。然后转到另一个页面提交表单并将 test 更新为 true 并再次加载 /hello。所以这一次它应该提醒真实(当我检查数据库时它已经更新为真实)但是当我测试它时它不会提醒任何东西。如果你让我知道什么时候做错了,那就太好了!

这是我的 app.js 中的相关代码

app.post("/Submitted", function(req,res){ 
    var conditions = mongoose.model('users').findOne({username: req.session.user.username}, function (err, doc){
      doc.test = true;
      doc.save();
        res.redirect('hello');
    });


app.get('/hello', function (req, res) {
    var umbrella = req.session.user.test;
    if (req.session.user) {
        res.render('5points', {test: test});
    } else {
        res.redirect('/');
    }
});

这是我的玉文件:

script.
  function check() {
    var test= !{JSON.stringify(test)};
    alert(test);
body(onload= "check()")

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    在 doc.save 完成之前触发 res.redirect('hello')。记住 node.js 是非阻塞 I/O。所以你需要在 回调中调用 res.redirect保存。

    app.post("/Submitted", function(req, res) {
        var conditions = mongoose.model('users').findOne({
                username: req.session.user.username
            }, function(err, doc) {
                doc.test = true;
                doc.save(function(err) {
                    if (err) return res.json(message: "error");
                    res.redirect('hello');
                });
            }
        });
    });
    

    【讨论】:

    • 您好,感谢您的回复。我试过这个。现在它会提醒它,但它会提醒它 false 而不是 true,尽管它已经在数据库中更新了它。
    • 真的会是会话没有更新吗?!因为如果用户再次登录它工作正常!无论如何要更新会话?!
    猜你喜欢
    • 2020-09-26
    • 2016-01-07
    • 2017-06-21
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2019-09-13
    相关资源
    最近更新 更多