更新时间:2023-02-14 10:37:56
创建单个查询来执行要删除的集合及其相关集合的删除操作是非常困难的.但是,您可以做的是:
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>
_id
value of the venue
document. You can use findByIdAndRemove()
which will also give you the deleted venue
document._id
of this venue
document you can query the Reviews
collection to delete all the Reviews
document that has _id
of venue
in its venue
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
.