Jake 1986 Jake 1986 - 1 month ago 6
Node.js Question

How to $set new Date() in MongoDB?

I have tried quite a few combinations and checked the MongoDB 3.2 docs, but I still am not getting my new Date() stored in my DB. Everything else below is getting properly stored. Thanks in advance for any tips!

Code from my app.js file:

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

Answer

Your update method is being called the wrong way, the update operators $set and $push should be in the same document. Re-write your method as:

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