Javascript 使用mongoose从mongodb集合中的文档数组中删除对象
我尝试从对象的数组属性中删除元素。 这是我的模式:Javascript 使用mongoose从mongodb集合中的文档数组中删除对象,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我尝试从对象的数组属性中删除元素。 这是我的模式: const userSchema = new mongoose.Schema({ userID: { type: Number }, name: { type: String }, names: [ { text: { type: String, required: true }, order: { type: Number,
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');
})
根据mongoose remove操作的文档,请参阅$pull运算符,该操作仅在通过回调时执行。要强制执行而不回调,必须首先调用
remove()
,然后使用exec()
方法执行
由于您试图从对象数组中删除对象,所以最好使用pull操作符。您不必进行查找和删除,只需使用更新方法即可
根据的文档,您可以指定值或条件
i、 e
mongoose with promise不需要使用exec(),我们可以直接使用then(),只使用remove操作符而不传递回调,或者使用promise(不使用then)而不执行remove。在这种情况下,我们必须使用exec来执行查询,例如
const query=Model.find().remove({name:'Anne Murray'})
这不会执行,因为没有传递回调。我尝试了此解决方案,但它删除了所有名称数组项!:/在我的测试名称=[{text:'aaa',order:1},{text:'bbb',order:2},{text:'ccc',order:3}],我将elemMatch与{order:2}一起使用,如果在$elemMatch表达式中指定单个查询谓词,则不需要$elemMatch。所以您可以简单地指定{$pull:{order:2}。$pull表达式将条件应用于结果数组的每个元素,就像它是顶级文档一样。我想这应该对你有用。你能分享一下你尝试过什么吗?我也尝试过这个解决方案,但它删除了我测试名称中的所有名称数组项:=[{text:'aaa',order:1},{text:'bbb',order:2},{text:'ccc',order:3}],我使用elemMatch和{order:2}
{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
User.update(
{ _id: Number(req.params.id) },
{ $pull: { 'names': { $elemMatch: { 'text': "john", 'order': 3 }} } },
(error, success) => {
if (error) console.log(error);
console.log(success);
}
);