[英]delete object from document array in mongodb collection using mongoose
我尝试从对象的数组属性中删除一个元素。 这是我的模式:
const userSchema = new mongoose.Schema({
userID: {
type: Number
},
name: {
type: String
},
names: [
{
text: { type: String, required: true },
order: {
type: Number,
required: true
}
}
]
});
这是我的猫鼬功能:
User.findOne({ userID: Number(req.params.id) })
.then((user) => {
user.names.remove({text: "john", order: 3});
recipe.save(() => {
res.json(recipe);
});
})
我不明白为什么它不好:/
要从文档中的数组中删除元素,请按照以下步骤操作
User.update(
{
userID: Number(req.params.id),
},
{
$pull: { names: { $elemMatch: { text: "john", order: 3 } } }
},
{
multi: false
}
).lean().then((Status) => {
console.log("Status-->", Status);
res.json('Removed Successfully');
})
在链接中参考$ pull运算符
根据猫鼬删除方法的文档,删除操作仅在传递回调时才执行。 要强制执行而没有回调,必须首先调用remove()
,然后使用exec()
方法执行它。
由于您尝试从对象数组中删除,因此最好使用pull运算符。 您无需查找和删除,只需使用更新方法即可。
根据$ pull运算符的文档,您可以指定值或条件
即
{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
在您的方案中,您需要指定一个或多个名称项对象的完整值或与一个或多个名称项匹配的条件
添加条件,在其中匹配名称项的ID,或者如果您不知道该条件,则可以使用elemMatch在少数字段上进行匹配,即
使用以下拉条件解决此问题:
User.update(
{ _id: Number(req.params.id) },
{ $pull: { 'names': { $elemMatch: { 'text': "john", 'order': 3 }} } },
(error, success) => {
if (error) console.log(error);
console.log(success);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.