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)
});
});