0

The scenario is I have a User model that has an array called filedLeaves which contains ObjectId's that are referenced on another collection. What I want to do is also remove those ObjectIds from its collection once that specific user is removed.

Here's my User Model

var schema = new Schema({
  fullName: {
    type: String,
    required: true,
    unique: true
  },
  leaveCredits: {
    type: Number
  },
  filedLeaves: [{
    type: Schema.Types.ObjectId,
    ref: 'Leave'
  }]
}, {
  usePushEach: true
});

And my Leave Model

var schema = new Schema({
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  status: {
    type: String,
    required: true
  },
  start: {
    type: String,
    required: true
  },
  end: {
    type: String,
    required: true
  },
  type: {
    type: String,
    required: true
  }
});

I tried this on my User model but it doesn't seem to work.

schema.post('remove', function (user) {
  user.filedLeaves.forEach(id => {
    Leave.findByIdAndRemove(id)
  });
});
Nar
  • 127
  • 4
  • 15
  • So you can delete a list instead of looping, and you also want "pre" middleware and not "post", since "post" means the document is already gone. Remember that's a model method and not an instance call, so the document need not be currently loaded in memory and you need all hooks to actually fetch the data first. – Neil Lunn May 31 '18 at 08:34
  • @NeilLunn How do I let the $in operator to delete everything that's in the array instead of listing them manually? – Nar May 31 '18 at 08:48

0 Answers0