Search code examples
node.jsmongodbmongoose

Mongoose post middleware triggers deleteMany


I have 2 Mongoose collections (User and Property). A user can have multiple properties and multiple users can have the same property. On deletion of a User, I would like to delete his referenced properties (only the ones that are not referenced by another user).

These are the two collections

model/User.js

const userSchema = new mongoose.Schema({
  first_name: { type: String, default: null },
  last_name: { type: String, default: null },
  email: { type: String, unique: true },
  password: { type: String },
  token: { type: String },
  properties: [{ type: Schema.Types.ObjectId, ref: 'property' }]
});

userSchema.post('findOneAndDelete', function(doc) {
  Property.deleteMany({_id: { $in: doc.properties }});
});

module.exports = mongoose.model("user", userSchema);

model/Property.js

const propertySchema = new mongoose.Schema({
  name: {
    type: String,
    unique: true
   },
  type: {
    type: String,
    enum: ['house', 'apartment', 'room' ,'parking', 'pool']
  },
  numberOfBedrooms: { type: Number },
  numberOfBathrooms: { type: Number },
  maxNumberOfGuests: { type: Number }
});

module.exports = mongoose.model("property", propertySchema);

On my User controller, when I try to use findOneAndDelete it activates the post for "findOneAndDelete" but does not perform the deletion of the referenced properties. Do you know why ? And do you have any idea about how to delete just the properties that are not referenced anywhere else ?

Thank you a lot ! Louie


Solution

  • Try await Property.deleteMany({_id: { $in: doc.properties }}). Property.deleteMany() returns a thenable, which needs to be called with await or .then(), unlike a regular promise. I believe you can also use .exec() in Mongoose.