Updating mongo collection using mongoose findOneAndUpdate
I have the following diagram and insert works 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 to update the second item in an exam so that the result is
{
"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 like this
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var examSchema = new Schema({
uid: String,
exams: []
});
module.exports = mongoose.model('Exam',examSchema);
I tried this update request but gets an error like
Exam.findOneAndUpdate({ _id:uid, exams.chapter_id: chapterId }, { exams.status:'passed})
^
SyntaxError: Unexpected token
...
+3
BluezTechz
source
to share
2 answers
Found a way. Since my subdoc filed "chapter_id" this is the ObjectIDID of the MongoDB object, we need to pass 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 Grinall
+3
BluezTechz
source
to share
I think you need to enclose exams.chapter_id in quotes:
"exams.chapter_id"
+3
John Greenall
source
to share