简体   繁体   English

如何从mongo数据库中完全删除文档的子文档

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

I'm trying to delete a mongodb object and then once deleted, I want to delete everything associated with that mongodb object. 我试图删除一个mongodb对象,然后删除后,我想删除与该mongodb对象相关的所有内容。 Including nested mongodb objects from my mongo database. 包括我的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"
      }
   ],
});

So I am trying to delete the parentObject, and childObjects that come along with it. 所以我试图删除parentObject和它附带的childObjects。 Not sure how I would go about doing that. 不知道我该怎么做。 I am successful in deleting the parentObject but that childObject is still in the mongodb, taking up space. 我成功删除了parentObject,但是childObject仍然在mongodb中,占用了空间。 Any ideas? 有任何想法吗?

MongoDB doesn't provide the notion of foreign keys like other databases do. MongoDB不像其他数据库那样提供外键的概念。 Mongoose has convenience methods in the client library that populates your documents with other documents using multiple queries and joining the results: Mongoose在客户端库中具有便捷的方法,该方法使用多个查询并结合结果将您的文档与其他文档一起填充:

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

If you want to do a cascading deletion then you'll need to grab the object ids of the children in the parent documents you want to delete, and then execute a delete against those children documents. 如果要进行级联删除,则需要在要删除的父级文档中获取子级的对象ID,然后对这些子级文档执行删除。

Here's a simplified example: 这是一个简化的示例:

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