gpt4 book ai didi

javascript - 如何从 Mongoose 中的数组中删除嵌套对象

转载 作者:行者123 更新时间:2023-11-30 09:40:18 25 4
gpt4 key购买 nike

这是我的第一个 Web 应用程序,我需要删除一个嵌套的数组项。您将如何使用此模式删除 Mongoose 中的对象:

User: {
event: [{_id:12345, title: "this"},{_id:12346, title:"that"}]
}

如何删除 mongoose/Mongo 中的 id:12346

最佳答案

使用$pull从下面的项目数组中删除项目:

db.User.update(
{ },
{ $pull: { event: { _id: 12346 } } }
)

The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

第一个参数中的空对象是用于查找文档的query。上面的方法删除了集合中所有文档中event数组中_id:12345的项。如果数组中有多个项目符合条件,请将 multi 选项设置为 true,如下所示:

db.User.update(
{ },
{ $pull: { event: { _id: 12346 } } },
{ multi: true}
)

关于javascript - 如何从 Mongoose 中的数组中删除嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41430675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com