简体   繁体   中英

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. Including nested mongodb objects from my mongo database.

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. 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. Any ideas?

MongoDB doesn't provide the notion of foreign keys like other databases do. Mongoose has convenience methods in the client library that populates your documents with other documents using multiple queries and joining the results:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM