使用$ pull从嵌套数组中删除项⇒
嘿我有一个问题,从我的数据库中删除嵌套数组,我想使用findOneAndUpdate
和$pull
。我的意思是从reply
阵列中删除项目。我尝试通过_id
找到评论项目并删除此回复项目,但这不起作用。请看下面我的代码。
我的架构
var productSchema = new Schema({ description: [{
type: String,
require: true,
}],
comments: [{
body: {
type: String,
trim: true,
},
author: {
type: String,
},
date: {
type: Date,
},
reply: [{
body: {
type: String,
trim: true,
},
author: {
type: String,
}, date: {
type: Date,
}
}]
}]
});
API
router.put('/dashboard/admin/komentarz/odpowiedz/usun/', function(req, res) { var currentCourse = req.body._id; // main item id
var deleteReply = req.body.reply; // reply item id
var commentId = req.body.commentId // comments item id
Product.findOneAndUpdate({ _id: currentCourse }, { $pull: { reply: req.body.reply }}, function(err, product){
//some code
})
回答:
拿裁判从Mongoose, pull from subdocument
Product.findOneAndUpdate({ _id: currentCourse,
// make sure sub document have a unique field let take _id
"comments._id" : 'commentId'
},
{
$pull: {
"comments.$.reply": {
_id:'replyId'
}
}
},
{
upsert:false,
new:true
}, function(err, product){
//some code
})
以上是 使用$ pull从嵌套数组中删除项⇒ 的全部内容, 来源链接: utcz.com/qa/260288.html