我设计了以下架构,插入工作正常
{
"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
}
如何更新考试键中的第二个元素,以便结果为
{
"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
答案 0 :(得分:3)
我认为你需要在引号中包含exams.chapter_id:
"exams.chapter_id"
答案 1 :(得分:3)
找到了办法。 自从我的suboc提交" 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);
});