0

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 }
  },
  department:{type: mongoose.Schema.Types.ObjectId,ref:'Department'},
  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?

Edit: Failed to add department field in User Schema

2 Answers2

0

I don't think you need to do any looping.

Have you tried something like this?

var User = require(/* etc */);

DeparmentSchema.pre('remove', function (next) {
    console.log('deleting department', this);
    User.remove({ 
        _id: { $in: this.employees } // this.employees must be an array of ObjectIds
    }, function (err) {
        console.log(err);
        if (err) return next(err);
        next();
    });
});

Ensure also that you are using .remove() to trigger the hook.

Mikey
  • 6,728
  • 4
  • 22
  • 45
  • A field got deleted while pasting the schema for user. User has a field called department that failed to add. The problem is Department is included in User, so if I requite User in department it's going to cause problem when running the code. – Mohammed Rashid May 03 '17 at 11:40
  • [`require` is always `require once`](http://stackoverflow.com/a/8958113/1022914) - so there shouldn't be any problems using `require` again. – Mikey May 03 '17 at 16:52
  • If you don't want to `require`, then you can replace `User.remove` with `this.model('User').remove` (as you have done in your answer). – Mikey May 03 '17 at 16:59
0

I solved the issue using this pre hook

DepartmentSchema.pre('remove', function(next) {
    var self=this;
    this.employees.forEach(function(employee){
        self.model('User').remove({ _id: employee },function (err) {
            if(err){
                return next(err)
            }
        });
    });
    next();

 });
  • Be careful... `remove` is asynchronous whereas `forEach` is not. You should always wait till the asynchronous operation is completed before proceeding. – Mikey May 03 '17 at 16:56