猫鼬删除(拉出)数组中的文档,不适用于ObjectID [英] Mongoose deleting (pull) a document within an array, does not work with 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) {
...
});
这篇关于猫鼬删除(拉出)数组中的文档,不适用于ObjectID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!