简体   繁体   English

如何从猫鼬的数组中删除嵌套对象

[英]How to remove nested objects from an array in Mongoose

This is my first web application and I need to delete a nested array item. 这是我的第一个Web应用程序,我需要删除一个嵌套数组项。 How would you delete an object in Mongoose with this schema: 您将如何使用以下模式在Mongoose中删除对象:

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

How can I go about deleting id:12346 in mongoose/Mongo? 我该如何删除id:12346 / Mongo中的id:12346

Use $pull to remove items from an array of items like below : 使用$ 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. $ pull运算符从现有数组中删除一个或多个与指定条件匹配的值的所有实例。

Empty object in the first parameter is the query to find the documents. 第一个参数中的空对象是用于查找文档的query The above method removes the items with _id: 12345 in the event array in all the documents in the collection. 上面的方法在集合中所有文档的event数组中删除带有_id: 12345的项目。 If there are multiple items in the array that would match the condition, set multi option to true as shown below : 如果数组中有多个符合条件的项目,则将multi选项设置为true,如下所示:

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

Findone will search for id,if not found then err otherwise remove will work. Findone将搜索id,如果找不到,则err否则删除将起作用。

   User.findOne({id:12346}, function (err, User) {
        if (err) {
            return;
        }
        User.remove(function (err) {
            // if no error, your model is removed
        });
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM