node.js - 如何在 MongoDB 中 $set new Date() ?

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

最佳答案

您的更新方法被错误地调用,更新运算符$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);
    }
);

关于node.js - 如何在 MongoDB 中 $set new Date() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40028977/

相关文章:

mongodb 2.4.9版本,无法启动mongodb服务

javascript - Jade : get variable in Bootstrap Modal

html - 如何在 Express 中使用 HTML 作为 View 引擎?

node.js - node.js 是否支持产量?

node.js - Webshot 在 DigitalOcean Ubuntu 14.04 中的 Meteor 上失败

mongodb - mgo bson 编码是否保证保留结构组件的顺序?

MongoDB - 基于非唯一字段的分页

node.js - Node Express RESTful API默认引擎用于错误处理

node.js - 如何从中间件获取api结果到路由

javascript - emacs缓冲区中的node.js没有进程——更好的系统在emacs中交互式执行js