Mongoose-如何从$pull中删除元素
我有猫鼬Mongoose-如何从$pull中删除元素,mongoose,Mongoose,我有猫鼬 var postSchema = new Schema({ comments: [{ nickName: {type: String, required: true}, comment: {type: String, required: true} }] }); 然后我想拉一条评论 Post.findOneAndUpdate({'_id': req.body._id}, {$pull: {'comments': {'_id': req
var postSchema = new Schema({
comments: [{
nickName: {type: String, required: true},
comment: {type: String, required: true}
}]
});
然后我想拉一条评论
Post.findOneAndUpdate({'_id': req.body._id}, {$pull: {'comments': {'_id': req.body._idComment} }},
function(err, data) {
if (err) {
res.send({status:400});
} else {
// how get $pull object if I don't know index of element of array
// data returns all objects
}
});
没有直接的方法可以做到这一点。但几乎没有解决办法。 更新数据(我的意思是删除它),如果成功,那么您就知道删除元素的输入就是您的答案
Post.update({'_id': req.body._id},
{$pull: {'comments': {'_id': req.body._idComment} }},function(err, data) {
....
....
});
您还可以运行find
查询,检查您的数据是否已删除,这也将确认您已删除的数据
否则,findOneAndUpdate
使用{new:True}
选项返回更新的文档,您可以将输入与返回的文档进行比较,以获取删除的数据