From Mongoose JS documentation:
schema.post('save', function (doc) { console.log('%s has been saved', doc._id); })
Is there any way to determine whether this is the original save or the saving of an existing document (an update)?
$isNew is how Mongoose determines whether save() should use insertOne() to create a new document or updateOne() to update an existing document.
save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.
save() is considered to be an instance method of the model, while the . create() is called straight from the Model as a method call, being static in nature, and takes the object as a first parameter.
Sponsor #native_company# — #native_desc# Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins.
@aheckmann reply at github
schema.pre('save', function (next) { this.wasNew = this.isNew; next(); }); schema.post('save', function () { if (this.wasNew) { // ... } });
isNew
is an key used by mongoose internally. Saving that value to the document's wasNew
in the pre save hook allows the post save hook to know whether this was an existing document or a newly created one. Additionally, the wasNew
is not commited to the document unless you specifically add it to the schema.
Edit: see Document#isNew for information on Document#isNew
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