node.js Mongoose 删除(拉)数组中的文档,不适用于 ObjectID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19786075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose deleting (pull) a document within an array, does not work with ObjectID
提问by psiphi75
I have the following mongoose schema:
我有以下猫鼬模式:
user = {
"userId" : "myId",
"connections":
[{
"dateConnectedUnix": 1334567891,
"isActive": true
}, {
"dateConnectedUnix": 1334567893,
"isActive": false
}]
}
I would like to delete the second item in the connectionsarray, to get the following:
我想删除connections数组中的第二项,以获得以下内容:
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)
});
But, I need to delete based on ObjectId. And the following goes does not work:
但是,我需要根据 ObjectId 进行删除。以下是行不通的:
userAccounts.update({'connections._id': '1234-someId-6789' },
{$pull: { 'connections._id': '1234-someId-6789' }},
function (err,val) {
console.log(val)
});
Any suggestions? I have been banging my head against the screen (aka Google, Stackoverflow, ...) for hours and have had no luck.
有什么建议?几个小时以来,我一直在用头撞屏幕(又名 Google、Stackoverflow ……),但没有成功。
回答by psiphi75
It seems that the above code would not work. It should not even have worked for the first example I gave.
上面的代码似乎不起作用。它甚至不应该适用于我给出的第一个例子。
In the end I was supported by this answer here: MongoDB, remove object from array
最后,我在这里得到了这个答案的支持:MongoDB, remove object from array
Here is my working code:
这是我的工作代码:
userAccounts.update(
{ userId: usr.userId },
{ $pull: { connections : { _id : connId } } },
{ safe: true },
function removeConnectionsCB(err, obj) {
...
});
回答by Deepak Sisodiya
I have a document like
我有一个像
I have to delete address from address array
我必须从地址数组中删除地址
After searching lots on internet I found the solution
在互联网上搜索了很多之后,我找到了解决方案
Customer.findOneAndUpdate(query, {$pull: {address: addressId}}, function(err, data){
if(err) {
return res.status(500).json({'error' : 'error in deleting address'});
}
res.json(data);
});
回答by throrin19
To use update with ObjectId, you should use ObjectId object instead of string representation :
要将更新与 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)
});
回答by user9457226
user: {
_id: ObjectId('5ccf3fa47a8f8b12b0dce204'),
name: 'Test',
posts: [
ObjectId("5cd07ee05c08f51af8d23b64"),
ObjectId("5cd07ee05c08f51af8d23c52")
]
}
Remove a single post from posts array
从帖子数组中删除单个帖子
user.posts.pull("5cd07ee05c08f51af8d23b64");
user.save();
user.posts.pull("5cd07ee05c08f51af8d23b64");
user.save();
回答by chenop
mongoose: 4.11.11
What have worked for me is the following syntax:
猫鼬:4.11.11
对我有用的是以下语法:
const removeTansactionFromUser = (userId, connectionId) => {
return User.findByIdAndUpdate(userId, { $pull: { "connections": connectionId} }, {'new': true} );
};
Mongoose support id in string format or ObjectId format.
Tip: new ObjectId(stringId)to switch from string to ObjectId
Mongoose 支持字符串格式或 ObjectId 格式的 id。
提示:new ObjectId(stringId)从字符串切换到 ObjectId
回答by WasiF
You can do it in mongoose 5.4.x
你可以在 mongoose 5.4.x
const result = await User.findByIdAndUpdate(user_id,
{
$pull: {
connections: { _id: con_id }
}
}, { new: true });
if (result)
console.log(result)
The itemfrom connectionsarray will be removed based on provided property _idvalue
在item从connections阵列将被删除基于提供的属性_id值
回答by biscarrosse
In mongoose 5.8.11, this $pull: { ... }didn't work for me, so far not sure why. So I overcame it in my controller this way:
在猫鼬 5.8.11 中,这$pull: { ... }对我不起作用,目前不知道为什么。所以我以这种方式在我的控制器中克服了它:
exports.removePost = async (req, res, next) => {
const postId = req.params.postId;
try {
const foundPost = await Post.findById(postId);
const foundUser = await User.findById(req.userId);
if (!foundPost || !foundUser) {
const err = new Error(
'Could not find post / user.',
);
err.statusCode = 404;
throw err;
}
// delete post from posts collection:
await Post.findByIdAndRemove(postId);
// also delete that post from posts array of id's in user's collection:
foundUser.posts.pull({ _id: postId });
await foundUser.save();
res.status(200).json({ message: 'Deleted post.' });
} catch (err) {
// ...
}
};


