i have a collection which have many document each of which have a subdocument array
comment : {
_id : ObjectId
name : String,
comments : [commentSchema]
}
commentSchema : {
_id : ObjectId,
commentType : String // can be either 'string' or 'image'
commentData : String
}
Now i want to delete all the subdocuments in path of 'comments', which is of commentType = 'image', from the whole comment collection.
I have done the following
export.removeComments = function(next) {
mongoose.model('comment').find({}, function(err,docs){
if(err) return next(err);
docs.forEach(function(doc, index){
doc.comments.pull({ commentType : 'image'});
//Following also not works
/* var comments = doc.comments;
for(var i =0; i < comments.length; i++ ) {
if(comments[i].commentType == 'image')
doc.comments.remove(comments[i]._id);
}*/
if(index < docs.length - 1) doc.save();
else doc.save(next);
});
});
};
But above has no effect.
Any help??
The following worked for me :
just added toString() with corresponding subdocument id as it was an Object not a string. and perhaps removing subdocument requires string of the id. Correct me if i am wrong.
mongoose.model('comment').find({}, function(err,docs){
if(err) return next(err);
docs.forEach(function(doc, index){
for(var i =0; i < comments.length; i++ ) {
if(comments[i].commentType == 'image')
doc.comments.remove(comments[i]._id.toString());
}
if(index < docs.length - 1) doc.save();
else doc.save(next);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.