ianaya89
ianaya89

Reputation: 4233

Execute a model operation inside a different model hook using mongoose

I want to trigger a remove operation to a ModelB inside a mongoose pre.save hook from a ModelA.

Basically any time any ModelA is updated, I need to drop the ModelB collection:

This is what I tried, I don't get errors but the operations never ends:

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;

const permissionSetSchema = require('./permission-set');
const PermissionSet       = mongoose.model('PermissionSet', permissionSetSchema);

const roleSchema = new Schema({
  name       : {  type: String, required: true, unique: true, maxLength: 140 },
  description: {  type: String, maxLength: 300 },
});

roleSchema.post('update', (next, done) => {
  PermissionSet.remove({}, err => {
    if (err) { next(err); }

    next();
  });
});

Upvotes: 0

Views: 116

Answers (1)

Amiram Korach
Amiram Korach

Reputation: 13286

The first arg is the document. The second is the next callback. Should be:

roleSchema.post('update', (doc, next) => {
  PermissionSet.remove({}, err => {
    if (err) { next(err); }

    next();
  });
});

http://mongoosejs.com/docs/middleware.html

Upvotes: 1

Related Questions