且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从单个查询mongodb中的所有集合中删除特定的ID

更新时间: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:

  1. 使用venue文档的_id值删除场所文档.您可以使用findByIdAndRemove(),它还会为您提供已删除的venue文档.
  2. 使用此venue文档的_id,您可以查询Reviews集合,以删除其venue属性中具有venue _id的所有Reviews文档作为参考. /li>
  1. Remove the venue document using the _id value of the venue document. You can use findByIdAndRemove() which will also give you the deleted venue document.
  2. Using the _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.