I have a collection with a following data:
{
"__v": NumberInt(0),
"_id": ObjectId("565443b1172e19d51f98b0ed"),
"address": "tohana",
"comments": [
{
"_id": ObjectId("5654455fe088d89c20736e3c"),
"comment": "good man",
"uemail": "dinesh@gmail.com",
"uname": "dinesh"
},
{
"_id": ObjectId("565445e471dce6ca20705a84"),
"comment": "nice person",
"uemail": "kr@gmail.com",
"uname": "krishan"
},
{
"_id": ObjectId("5654460e7aa73bec2064060e"),
"comment": "bad person",
"uemail": "Rai",
"uname": "Rahul"
}
],
"email": "nishantg@ocodewire.com"▼,
"name": "Nishant"
}
Can anyone suggest how to remove a subdocument from a 'comments' key having only id of subdocument, I am going to del? for instance i want to del a subdocument with id 5654455fe088d89c20736e3c
So this subdocument should be deleted.
Here is code i am using:
var Users = require("../app/models/users"); //userModel
app.post('/deleteComment/:id', function(req, res) {
var input = JSON.parse(JSON.stringify(req.body));
var id = req.params.id;//commentId
var userId = input.id;//userId
Users.findByIdAndUpdate(userId, {
'$pull': {
'comments':{ '_id': new ObjectId(someStringValue) }
}
});
});
But this does not delete data.
Karan,
You would have to make a small adjustment to your code. Your update criteria needs to be wrapped in an object comparing field
to key
.
app.post('/deleteComment/:id', function(req, res) {
var commentId = req.params.id; //commentId
var userId = req.body.id; //userId
UserAlerts.findOneAndUpdate(
{userId: userId},
{$pull: {comments: {_id: commentId}}},
function(err, data){
if(err) return err;
console.log(data);
});
});
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.