[英]Mongoose - remove array element in update
I have a JSON in this format: 我有以下格式的JSON:
{
_id:5522ff94a1863450179abd33,
userName:'bill',
__v:3,
friends:[
{
_id:55156119ec0b97ec217d8197,
firstName:'John',
lastName:'Doe',
username:'johnDoe'
},
{
_id:5515ce05207842d412c07e03,
lastName:'Adam',
firstName:'Foo',
username:'adamFoo'
}
]
}
And I would like to remove whole corresponding subarray. 我想删除整个相应的子数组。 For example I want to remove user John Doe with ID
55156119ec0b97ec217d8197
so the result will be: 例如,我要删除ID为
55156119ec0b97ec217d8197
用户John Doe,因此结果将是:
{
_id:5522ff94a1863450179abd33,
userName:'bill',
__v:3,
friends:[
{
_id:5515ce05207842d412c07e03,
lastName:'Adam',
firstName:'Foo',
username:'adamFoo'
}
]
}
So far I have this: 到目前为止,我有这个:
exports.delete = function (req, res) {
var friends = req.friends[0];
friends.update(
{'_id': req.body.friendsId},
{$pull: {'friends.friends': {_id: req.body.friendId}}}, function (err) {
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.json(friends);
}
});
};
But without result and also I'm not getting any error, it will stay just same as before. 但是没有结果,而且我也没有收到任何错误,它将和以前一样。
req.body.friendsId
is ID of main array and req.body.friendId
is ID of specific user which I want to pull. req.body.friendsId
是主数组的ID, req.body.friendId
是我要提取的特定用户的ID。
Change your update query to this: 将更新查询更改为此:
exports.delete = function (req, res) {
var friends = req.friends[0]; // assuming the friends object is your mongodb collection
friends.update(
{ '_id': req.body.friendsId },
{ $pull: {'friends': { _id: req.body.friendId } } }, function (err) {
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.json(friends);
}
});
};
This will search for documents which have the friends array element _id
value = req.body.friendsId
and removes the specific array element from that array using the $pull
operator. 这将搜索具有friends数组元素
_id
值= req.body.friendsId
文档,并使用$pull
运算符从该数组中删除特定的数组元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.