Mongoose删除(拉)数组中的文档,不适用于ObjectID

psi*_*i75 23 mongoose mongodb node.js

我有以下mongoose架构:

user = {
    "userId" : "myId",
    "connections":
    [{
        "dateConnectedUnix": 1334567891,
        "isActive": true
    }, {
        "dateConnectedUnix": 1334567893,
        "isActive": false
    }]
}
Run Code Online (Sandbox Code Playgroud)

我想删除connections数组中的第二项,以获得以下内容:

user = {
    "userId" : "myId",
    "connections": 
    [{
        "dateConnectedUnix": 1334567893,
        "isActive": false
    }]
}
Run Code Online (Sandbox Code Playgroud)

以下代码按预期执行工作:

userAccounts.update({'connections.isActive': false }, 
                    {$pull: { 'connections.isActive':false }}, 
                    function (err,val) {
                        console.log(val)
                    });
Run Code Online (Sandbox Code Playgroud)

但是,我需要基于ObjectId删除.而以下行为不起作用:

userAccounts.update({'connections._id': '1234-someId-6789' }, 
                    {$pull: { 'connections._id': '1234-someId-6789' }}, 
                    function (err,val) {
                        console.log(val)
                    });
Run Code Online (Sandbox Code Playgroud)

有什么建议?我一直在屏幕上撞击屏幕(又名谷歌,Stackoverflow,......)几个小时,没有运气.

psi*_*i75 38

看来上面的代码不起作用.它甚至不应该适用于我给出的第一个例子.

最后我得到了这个答案的支持:MongoDB,从数组中删除对象

这是我的工作代码:

userAccounts.update( 
      { userId: usr.userId },
      { $pull: { connections : { _id : connId } } },
      { safe: true },
      function removeConnectionsCB(err, obj) {
          ...
      });
Run Code Online (Sandbox Code Playgroud)

  • 和`connId`和`usr.userId`是`ObjectId`的实例? (2认同)

小智 14

我有一个类似的文件

在此输入图像描述

我必须从地址数组中删除地址

在网上搜索了很多我找到了解决方案

 Customer.findOneAndUpdate(query, {$pull: {address: addressId}}, function(err, data){
        if(err) {
          return res.status(500).json({'error' : 'error in deleting address'});
        }

        res.json(data);

      });
Run Code Online (Sandbox Code Playgroud)


小智 9

user: {
 _id: ObjectId('5ccf3fa47a8f8b12b0dce204'),
 name: 'Test',
 posts: [
  ObjectId("5cd07ee05c08f51af8d23b64"),
  ObjectId("5cd07ee05c08f51af8d23c52")
 ]
}
Run Code Online (Sandbox Code Playgroud)

从帖子数组中删除单个帖子

user.posts.pull("5cd07ee05c08f51af8d23b64"); user.save();


thr*_*n19 8

要使用ObjectId进行更新,您应该使用ObjectId对象而不是字符串表示:

var ObjectId = require('mongoose').Types.ObjectId;

userAccounts.update({'connections._id': new ObjectId('1234-someId-6789') }, 
                {$pull: { 'connections._id': new ObjectId('1234-someId-6789') }}, 
                function (err,val) {
                    console.log(val)
                });
Run Code Online (Sandbox Code Playgroud)

  • 我认为你的代码有点误导。例如,在第 3 行中,您编写了 `connections_.id`,而实际上原始问题清楚地表明 `connections` 是一个没有附加 `_id` 属性的对象数组。 (2认同)

Was*_*siF 7

用于findByIdAndUpdate从数组中删除一个项目

你可以这样做mongoose 5.4.x and above

const result = await User.findByIdAndUpdate(user_id, {
    $pull: {
        someArrayName: { _id: array_item_id }
    }
}, { new: true });
Run Code Online (Sandbox Code Playgroud)

将根据提供的属性_id值删除数组中的项目