Tuesday, 2 May 2017

Mongoose remove all referenced objectID elements using pre or post hook

I have two schemas

User Schema

var UserSchema = new mongoose.Schema({
  name: {
        first: { type: String, trim: true, required: true },
        last:  { type: String, trim: true, required: true }
  },
  image:{ data: Buffer, contentType: String },
  phone: {type:String, required: true},
  email: {type: String, required: true, unique:true},
});

Department Schema

var DeparmentSchema = new mongoose.Schema({
name:{ type: String, required: true },
date:{type:Date,default: Date.now},
employees:[{type: mongoose.Schema.Types.ObjectId,ref:'User'}] });

When a department gets deleted, all employees should also be deleted. I tried looping and deleting one by one. But it does not seem to the efficient way.

Can I remove all employee using mongoose pre or post hook in department schema?



via Mohammed Rashid

No comments:

Post a Comment