【问题标题】:Updating mongo collection using mongoose findOneAndUpdate使用 mongoose findOneAndUpdate 更新 mongo 集合
【发布时间】:2014-09-18 16:58:18
【问题描述】:

我设计了以下架构并且插入工作正常

  {
    "uid" : "541a5edaef7b20086c2c9ea0",
    "_id" : ObjectId("541a6bca735a20060c593813"),
    "exams" : [ 
        {
            "start_time" : "2014-09-18T05:21:14.219Z",
            "status" : "passed",
            "chapter_id" : ObjectId("54194290022f6d830f255f2e")
        }, 
        {
            "start_time" : "2014-09-18T05:26:14.219Z",
            "status" : "attending",
            "chapter_id" : ObjectId("54194290022f6d830f255f2f")
        }
    ],
    "__v" : 0
}

如何更新 exams 键中的第二个元素,以便结果为

{
        "uid" : "541a5edaef7b20086c2c9ea0",
        "_id" : ObjectId("541a6bca735a20060c593813"),
        "exams" : [ 
            {
                "start_time" : "2014-09-18T05:21:14.219Z",
                "status" : "passed",
                "chapter_id" : ObjectId("54194290022f6d830f255f2e")
            }, 
            {
                "start_time" : "2014-09-18T05:26:14.219Z",
                **"status" : "failed",**
                "chapter_id" : ObjectId("54194290022f6d830f255f2f")
            }
        ],
        "__v" : 0
    }

我的模型定义如下

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var examSchema = new Schema({
  uid: String,
  exams: []
});
module.exports = mongoose.model('Exam',examSchema);

我尝试了这个查询来更新,但是得到了类似的错误

Exam.findOneAndUpdate({ _id:uid, exams.chapter_id: chapterId }, { exams.status:'passed})
                                          ^
SyntaxError: Unexpected token 

.

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    我认为您需要将exams.chapter_id 括在引号中:

    "exams.chapter_id"
    

    【讨论】:

    【解决方案2】:

    找到了方法。 由于我的子文档提交的“chapter_id”是一个 MongoDB ObjectID,我们需要将它传递给类似

    var ObjectId = require('mongoose').Types.ObjectId;
    Exam.findOneAndUpdate({ _id: id, exams:{$elemMatch:{'chapter_id': new ObjectId(chapterId)}}}, { 'exams.$.status' : passStatus }, function(err,doc) {
        res.send(doc);
      });
    

    谢谢John Greenall

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 2016-10-15
      • 2016-09-13
      • 2017-05-06
      • 1970-01-01
      • 2017-10-14
      • 2014-01-07
      相关资源
      最近更新 更多