I have the following schema designed and insert is working fine
{
"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
}
How can i update the second element in exams key, so that the result will be
{
"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
}
My model is defined as follows
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var examSchema = new Schema({
uid: String,
exams: []
});
module.exports = mongoose.model('Exam',examSchema);
I tried this query to update ,but gets the error like
Exam.findOneAndUpdate({ _id:uid, exams.chapter_id: chapterId }, { exams.status:'passed})
^
SyntaxError: Unexpected token
.
I think you need to enclose exams.chapter_id in quotes:
"exams.chapter_id"
Found a way. Since my subdoc filed "chapter_id" is a MongoDB ObjectID we need to pass it something like
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);
});
Thanks John Greenall