I am seeking a way to activate a function every time an element is added or created in a collection, not when it's merely updated. (Also, I require the ID of the newly created element)
Here is my approach:
schema.pre("save", function() {
this.$locals.wasNew = this.isNew;
});
schema.post("save", function() {
if (this.$locals.wasNew) {
console.log(`User ${this.id} has been created!`);
}
});
This method works well with calls like this one:
await UserModel.create({
mail
});
However, it does not work as expected with calls such as this one:
const user = await UserModel.findOneAndUpdate(
{ mail },
{ $set: { mail } },
{ new: true, upsert: true }
);
It appears that the upsert
feature fails to trigger the save
hook with the isNew
boolean set to true.
Could there be an error in my implementation? Is something missing? Or perhaps there is another method to achieve this?