如何在MongoDB中设置新的Date()?

时间:2016-10-13 19:04:41

标签: node.js mongodb express

我已经尝试了很多组合并检查了MongoDB 3.2文档,但我仍然没有将我的新Date()存储在我的数据库中。下面的所有其他内容都正确存储。提前感谢任何提示!

我的app.js文件中的代码:

db.collection('users').update({user: req.user.username}, {
                    $push: {
                        "recentPlays": {
                            "quiz": req.session.mostRecentQuiz,
                            "score": score
                        }
                    }
                },{
                    $set: {
                        "mostRecentQuiz.quizObj": req.session.mostRecentQuiz,
                        "mostRecentQuiz.time"   : new Date() // StackOverflow: this is the part that is not getting stored in the DB.
                    }
                }, function (err, result) {
                    if (err) throw err;
                    console.log(result);
                });

1 个答案:

答案 0 :(得分:1)

您的更新方法调用方式错误,更新运算符$set$push应位于同一文档中。将您的方法重写为:

db.collection('users').update(
    { "user": req.user.username }, 
    {
        "$push": {
            "recentPlays": {
                "quiz": req.session.mostRecentQuiz,
                "score": score
            }
        }
        "$set": {
            "mostRecentQuiz.quizObj": req.session.mostRecentQuiz,
            "mostRecentQuiz.time"   : new Date() 
        }
    }, function (err, result) {
        if (err) throw err;
        console.log(result);
    }
);