簡體   English   中英

如何從mongo數據庫中完全刪除文檔的子文檔

[英]How to delete a sub-document of a document completely from the mongo database

我試圖刪除一個mongodb對象,然后刪除后,我想刪除與該mongodb對象相關的所有內容。 包括我的mongo數據庫中的嵌套mongodb對象。

var parentObjectSchema = new mongoose.Schema({
    name: String,
    split: Number,
    parts: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "ChildObjectSchema"
        }
    ],
});

var childObjectSchema = new mongoose.Schema({
    name: String,
    number: Number,
    things: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Things"
      }
   ],
});

所以我試圖刪除parentObject和它附帶的childObjects。 不知道我該怎么做。 我成功刪除了parentObject,但是childObject仍然在mongodb中,占用了空間。 有任何想法嗎?

MongoDB不像其他數據庫那樣提供外鍵的概念。 Mongoose在客戶端庫中具有便捷的方法,該方法使用多個查詢並結合結果將您的文檔與其他文檔一起填充:

https://mongoosejs.com/docs/populate.html

如果要進行級聯刪除,則需要在要刪除的父級文檔中獲取子級的對象ID,然后對這些子級文檔執行刪除。

這是一個簡化的示例:

const deleteThing = (thingId) => {
  thingObjectSchema.remove({ _id: thingId });
};

const deleteChild = (childId) => {
  childObjectSchema.findOne({ _id: childId }).select('things').lean().exec((err, child) => {
    for (const thingId of child.things) {
      deleteThing(thingId);
    }

    childObjectSchema.remove({ _id: childId });
  })
};

const deleteParent = (parentId) => {
  parentObjectSchema.findOne({ _id: parentId }).select('parts').lean().exec((err, parent) => {
    for (const childId of parent.parts) {
      deleteChild(childId);
    }

    parentObjectSchema.remove({ _id: parentId });
  })
};

// note: not actually tested

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM