简体   繁体   English

如何使用 Mongoose 从阵列中删除 object

[英]How to remove an object from an array using Mongoose

I have tried a lot of things but can't seem to get any of them to work as intended.我已经尝试了很多东西,但似乎无法让它们按预期工作。 Let's say I had something like the following.假设我有类似以下的内容。

{
      _id: '12345',
      name: 'John Smith',
      job: [
        {
             title: 'Web Developer',
             years: '12',
             status: 'not active',
         },
         {
             title: 'supervisor',
             years: '15',
             status: 'terminated',
         },
         {
             title: 'lead developer',
             years: '3',
             status: 'not active',
         },
         {
             title: 'Software Engineer',
             years: '9',
             status: 'active',
         },
      ]
 }

How can I remove the object with the status of 'terminated'?如何删除状态为“已终止”的 object? Also, would it be the same to remove all objects with that status of 'not active'?此外,删除所有状态为“未激活”的对象是否相同?

Thanks.谢谢。

You can use findOneAndUpdate with the $pull command.您可以将 findOneAndUpdate 与 $pull 命令一起使用。

Example:例子:

User.findOneAndUpdate({/* filter */}, { $pull: {array: {/* condition */}} });

More information:更多信息:

Wondering if the below would work as well....想知道下面是否也可以工作....

Model.findOneAndUpdate({'job.status' : "terminated"}, { $pull: job.$ }, {$multi : true});

Remove nested document using the $pull operator使用$pull运算符删除嵌套文档

var query = {
    _id: "12345"
};

var update = {
    $pull: {
        job: {
            status: {
                $in: ['terminated', 'not active']
            }
        }
    }
};

db.collection.update(query, update);

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

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