我有一个包含以下数据的集合:
{
"__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"
}
任何人都可以建议如何从只有子文档id的'comments'键中删除子文档,我要去del?
例如,我想del id一个id 5654455fe088d89c20736e3c
的子文档所以这个子文档应该被删除。
以下是我正在使用的代码:
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) }
}
});
});
但这不会删除数据。
答案 0 :(得分:0)
app.post('/deleteComment/:id', function(req, res) {
var input = JSON.parse(JSON.stringify(req.body));
var id = req.params.id;
var userId = input.uid;
Users.findOneAndUpdate(
{_id: userId},
{$pull: {comments: {_id: id}}},
function(err, data){
if(err) return err;
res.send({data:data});
});
})