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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With