从单个查询mongodb中的所有集合中删除特定的ID
我有评论集
{
"_id" : ObjectId("5ac47af5e935d927a03518ac"),
"venue" : ObjectId("5abc9436b7c99332f0a68136"),
"content" : "gfhfghfghfghf",
}
我有活动收藏
{
"_id" : ObjectId("5abce7208b9efa5a6b8e739b"),
"venue" : ObjectId("5abc9436b7c99332f0a68136"),
"description" : "22222222222222222222222222222222222222",
}
我收集了场地
{
"_id" : ObjectId("5abc9436b7c99332f0a68136"),
"name" : "ASA College - Manhattan Campus",
"addedBy" : ObjectId("5abc93a85d3914318cc8d3d7"),
"__v" : 0,
}
在删除相应的Venue
创建单个查询来执行要删除的集合及其相关集合的删除操作是非常困难的.但是,您可以做的是:
It is quite difficult to create a single query that performs the deletion action for the collection you want to delete and its related collection. But, what you can do is:
- 使用
venue
文档的_id
值删除场所文档.您可以使用findByIdAndRemove()
,它还会为您提供已删除的venue
文档. - 使用此
venue
文档的_id
,您可以查询Reviews
集合,以删除其venue
属性中具有venue
_id
的所有Reviews
文档作为参考. /li>
- Remove the venue document using the
_id
value of thevenue
document. You can usefindByIdAndRemove()
which will also give you the deletedvenue
document. - Using the
_id
of thisvenue
document you can query theReviews
collection to delete all theReviews
document that has_id
ofvenue
in itsvenue
property as a reference.
示例代码
Venue.findByIdAndRemove(idOfVenue, function (err, venueObj) {
if(err){
console.log('Error in deleting Venue');
} else {
Reviews.remove({venue: venueObj._id}, function (err) {
if (err) {
console.log('Error in deleting Reviews');
} else {
console.log('Record deleted successfully!!');
}
});
}
});
但是,您可以通过以下方式设置架构:删除venue
时,与该venue
关联的reviews
将从架构级别中删除.
But however you can set up your schema in such a way that when you remove venue
then reviews
associated with that venue
is deleted from the schema level.
// Remove Venue
Venue.remove({_id: vanueId}, function (err) {
if (err) {
console.log('Error in removing venue');
}
});
//Remove Reviews related to venue, this code is placed in Venue schema
VenueSchema.pre('remove', function(next) {
this.model('Reviews').remove({ venue: this._id }, next);
});
在remove
操作上使用pre
会首先从Reviews
集合中删除记录,然后从Venue
集合中删除记录.因此,您只有一个查询要删除Venue
记录.在Venue
的架构级别处理从Reviews
删除.
Using pre
on remove
operation will first remove the record from Reviews
collection and then remove a record from Venue
collection. Thus, You have only one query that is to remove the Venue
record. Removing from Reviews
is handled at the schema level of Venue
.