Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Mongoose pre-hooks not work with fat-arrow function syntax

I am trying to use a simple pre-hook Mongoose for deleting any references of a document like this:

PostSchema.pre("remove", async () => {
  await Comment.remove({ _postId: this._id }).exec();
  await User.update({ $pull: { _posts: this._id } }).exec();
});

The above fat arrow syntax does not seem to work - although the Post document is removed, the Comment and the User models are not updated accordingly. Instead, I had to use the old syntax (as per mongoose documentation) to get the hook to work properly such as this:

PostSchema.pre("remove", async function() {
  await Comment.remove({ _postId: this._id }).exec();
  await User.update({ $pull: { _posts: this._id } }).exec();
});

I am finding this rather strange, unless I am doing something wrong of course. Is this the expected behaviour?

like image 551
James Avatar asked Nov 18 '25 20:11

James


1 Answers

because this points to global scope, not function scope in arrow functions. In this case use function(){} instead

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

EDIT: similar question: https://stackoverflow.com/a/49441708/7526159

like image 82
Artur P. Avatar answered Nov 21 '25 10:11

Artur P.