'find and update one field in array of subdoc mongoose
i'm new in mongodb and mongoose. i'm using node js, and i want to find and update specific field in one of array in sub document. here is my data structure :
var PostSchema = new Schema({
title: String,
comment: [
{
name: String,
value: String
}
],
createdAt: Date,
updateAt: Date
})
this is my data example :
{
_id : 12,
title : 'some article here...',
comment : [{
_id : 1,
name : 'joe',
value : 'wow that fantastic...'
},{
_id : 2,
name : 'rocky',
value : 'really... thats insane...'
},{
_id : 3,
name : 'jane',
value : 'i think its impossible to do...'
}],
createdAt : 2016-04-14 04:50:54.760Z,
updatedAt : 2016-04-14 04:50:54.760Z
}
i need to update comment which have _id : 2, i want to change the value become 'what???'. i try to update with :
Post.findOne({'_id': 12, 'comment._id': 2}, {_id: 0, 'comment.$': 1}, function (err, cb) {
cb.comment.value = 'what???'
cb.save()
})
but it failed... so, can you help me? Thanks
Solution 1:[1]
you can use findOneAndUpdate and positional operator $ to update specific comment value
Post.findOneAndUpdate({"_id": 12, "comment._id": 2},
{
$set: {
"comment.$.value ": "New value set here"
}
},
{ new: true } // return updated post
).exec(function(error, post) {
if(error) {
return res.status(400).send({msg: 'Update failed!'});
}
return res.status(200).send(post);
});
Solution 2:[2]
It will work for array updation in mongodb using mongoose
Post.findOneAndUpdate(
{ id: 12,comment_id:2 },
{ $push: { comment:"new comment" } }
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shaishab Roy |
| Solution 2 | DIPIKESH KUMAR |
