Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether doc is new or exists in mongoose Post middleware's 'save'?

Tags:

mongoose

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)?

like image 925
Plywood Avatar asked Jun 13 '13 23:06

Plywood


People also ask

Is new in Mongoose?

$isNew is how Mongoose determines whether save() should use insertOne() to create a new document or updateOne() to update an existing document.

What does save () do in Mongoose?

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.

What is difference between save and create in Mongoose?

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.

What is .pre in Mongoose?

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.


2 Answers

@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.

like image 83
muZk Avatar answered Oct 07 '22 09:10

muZk


Edit: see Document#isNew for information on Document#isNew

like image 24
Plywood Avatar answered Oct 07 '22 08:10

Plywood