Mongoose 删除(拉)数组中的文档,不适用于 ObjectID [英] Mongoose deleting (pull) a document within an array, does not work with ObjectID

查看:25
本文介绍了Mongoose 删除(拉)数组中的文档,不适用于 ObjectID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下猫鼬模式:

user = {
    "userId" : "myId",
    "connections":
    [{
        "dateConnectedUnix": 1334567891,
        "isActive": true
    }, {
        "dateConnectedUnix": 1334567893,
        "isActive": false
    }]
}

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

I would like to delete the second item in the connections array, to get the following:

user = {
    "userId" : "myId",
    "connections": 
    [{
        "dateConnectedUnix": 1334567893,
        "isActive": false
    }]
}

以下代码按预期完成工作:

The following code does the job as expected:

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

但是,我需要根据 ObjectId 进行删除.以下是行不通的:

But, I need to delete based on ObjectId. And the following goes does not work:

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

有什么建议吗?我一直在用头撞屏幕(又名 Google、Stackoverflow 等)几个小时,但没有成功.

Any suggestions? I have been banging my head against the screen (aka Google, Stackoverflow, ...) for hours and have had no luck.

推荐答案

上面的代码好像不行.它甚至不应该适用于我给出的第一个例子.

It seems that the above code would not work. It should not even have worked for the first example I gave.

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

In the end I was supported by this answer here: MongoDB, remove object from array

这是我的工作代码:

userAccounts.update( 
    { userId: usr.userId },
    {
        $pull: {
            connections: { _id : connId }
        }
    },
    { safe: true },
    function removeConnectionsCB(err, obj) {
        // ...
    }
);

这篇关于Mongoose 删除(拉)数组中的文档,不适用于 ObjectID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆