Middleware pre('remove', ...) not getting called

2,135 views
Skip to first unread message

Mongo Rookie

unread,
Jun 25, 2013, 1:19:15 PM6/25/13
to mongoo...@googlegroups.com
I am executing the following code:

  User.findByIdAndRemove(id, function(err, user) {
    if (err) {
      console.log('could not delete user: ' + id);
    }

    callback(err, user);
  });


and it is not executing my pre remove.

UserSchema.pre('remove', function(next) {
    var user = this;

    Group.removeUserFromGroups(user, function(err, number) {
      next();
    });
});

In docs : Model.remove
Note:
This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, no middleware (hooks) are executed.

Does that also apply to Model.findByIdAndRemove?

I would like to have the find and remove execute in one call to mongo.  I.E. I don't really want to do
User.findById(id, function(err, user) {
   user.remove();
}

Is that my only option?

Jason Crawford

unread,
Jun 26, 2013, 12:10:22 AM6/26/13
to mongoo...@googlegroups.com
Well, in the documentation for findByIdAnd*Update*, it notes that middleware, validators, etc. are not applied. It says “if you need those features, use the traditional approach of first retrieving the document.” http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

The documentation doesn't say explicitly, but I'd guess the same is true for findByIdAndRemove.

-Jason

--
Blog: http://blog.jasoncrawford.org  |  Twitter: @jasoncrawford


--
Documentation - http://mongoosejs.com/
Plugins - http://plugins.mongoosejs.com/
Bug Reports - http://github.com/learnboost/mongoose
Production Examples - http://mongoosejs.tumblr.com/
StackOverflow - http://stackoverflow.com/questions/tagged/mongoose
Google Groups - https://groups.google.com/forum/?fromgroups#!forum/mongoose-orm
Twitter - https://twitter.com/mongoosejs
IRC - #mongoosejs
---
You received this message because you are subscribed to the Google Groups "Mongoose Node.JS ODM" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoose-orm...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Aaron Heckmann

unread,
Jun 28, 2013, 3:53:12 PM6/28/13
to mongoo...@googlegroups.com
Yes Jason is correct. I just updated the docs.

Stefano Pongelli

unread,
Aug 21, 2013, 9:37:27 AM8/21/13
to mongoo...@googlegroups.com
It would be nice if it was also added to the Middleware incipit. I was wondering the same and found this discussion by chance ;)

Stefano Pongelli

unread,
Aug 21, 2013, 9:54:02 AM8/21/13
to mongoo...@googlegroups.com
Actually, Middlewares only work on instances of Models (i.e. documents). This should be clarified a little in the description :)

Aaron Heckmann

unread,
Aug 21, 2013, 7:08:40 PM8/21/13
to mongoo...@googlegroups.com
done
Reply all
Reply to author
Forward
0 new messages