Home > Back-end >  How to delete related documents in mongodb like onDelete: cascade?
How to delete related documents in mongodb like onDelete: cascade?

Time:10-18

I use mongodb and mongoose ORM in my project. I have two related collections.

My first collection like this.

const Sensor: Schema = new Schema(
  {
    name: {
      type: String,
    },
    description: {
      type: String,
      default: null,
    },
    deviceId: {
      type: mongoose.Types.ObjectId,
      required: true,
      ref: 'Device',
    },
  },
  {
    timestamps: true,
    versionKey: false,
    collection: 'Sensor',
  }
);

Other collection like this.

const Device: Schema = new Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
    },
  },
  {
    versionKey: false,
    collection: 'Device',
  }
);

The sensor has the id of the device and this two collections are related.

When I delete a device, I want the associated sensors to be deleted as well. (like onDelete: cascade feature, in sequelize and typeorm)

How can I do it with mongoose? What's best practices for this issue?

CodePudding user response:

Implement the necessary middleware for cleaning up reference to related documents

For example, when using the Document.remove method to delete a device,
implement a post remove hook to remove all related sensors devices as follows:

Device.post('remove', function(doc, next) {

  // Deleting related sensors. 
  Sensor.deleteMany({ deviceId: doc._id })
    .then(() => next())
    .catch(next);
 
});
  • Related