Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mongoose post remove hook #226

Open
daenuprobst opened this issue Jan 1, 2018 · 2 comments
Open

Mongoose post remove hook #226

daenuprobst opened this issue Jan 1, 2018 · 2 comments

Comments

@daenuprobst
Copy link

Given that the post remove hook isn't called when a document is deleted (which is what should be expected due to the implementation), I wonder what would be the best way to achieve the deletion of references upon removal of a document. For example, if there are two schemas, users and groups, which model a n to n relationship where each user has an array of references to groups. A group is then removed so its objectId should be removed from all the users group array.

By mongoose design, the implementation of remove in service.js does not fire the remove hook, which means I cannot do the following in group.model.js:

module.exports = function (app) {
  const mongooseClient = app.get('mongooseClient');
  const { Schema } = mongooseClient;
  const groups = new Schema({

    name: { type: String, required: true },
    accessRights: [{
      resourceType: { type: String },
      resource: { type: Schema.Types.ObjectId, refPath: 'accessRights.resourceType' },
      actions: { type: [String], default: [] }
    }]
    
  }, {
    timestamps: true
  });

  groups.post('remove', function(doc) {
    // Remove doc._id from groups array in users
  });

  return mongooseClient.model('groups', groups);
};

What would be the best method to enable this behaviour?

@daffl
Copy link
Member

daffl commented Jan 1, 2018

It probably will work if you set the lean option to true.

You can also probably get the same functionality by using an after remove Feathers service hook.

@daenuprobst
Copy link
Author

As lean is set to true by default, I suppose you meant setting it to false. Either does not work. The "problem" is with mongoose middleware, which states

There is no query hook for remove(), only for documents. If you set a 'remove' hook, it will be fired when you call myDoc.remove(), not when you call MyModel.remove(). Note: The create() function fires save() hooks.

It is not a problem per se, but I wanted to keep this functionality as close as possible to mongoose / the model and I'm not sure if a service hook is the right place to do it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants