Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Mongoose provide access to previous value of property in pre('save')?

I'd like to compare the new/incoming value of a property with the previous value of that property (what is currently saved in the db) within a pre('save') middleware.

Does Mongoose provide a facility for doing this?

like image 649
smabbott Avatar asked Jul 11 '12 15:07

smabbott


People also ask

What is pre save in Mongoose?

The save() function triggers validate() hooks, because mongoose has a built-in pre('save') hook that calls validate() . This means that all pre('validate') and post('validate') hooks get called before any pre('save') hooks.

Does update call save in Mongoose?

When you create an instance of a Mongoose model using new , calling save() makes Mongoose insert a new document. If you load an existing document from the database and modify it, save() updates the existing document instead.

What does Mongoose model return?

mongoose. model() returns a Model ( It is a constructor, compiled from Schema definitions).

How does Mongoose work with MongoDB?

With Mongoose, you would define a Schema object in your application code that maps to a collection in your MongoDB database. The Schema object defines the structure of the documents in your collection. Then, you need to create a Model object out of the schema. The model is used to interact with the collection.


1 Answers

The accepted answer works very nicely. An alternative syntax can also be used, with the setter inline with the Schema definition:

var Person = new mongoose.Schema({   name: {     type: String,     set: function(name) {       this._previousName = this.name;       return name;     } });  Person.pre('save', function (next) {   var previousName = this._previousName;   if(someCondition) {     ...   }   next(); }); 
like image 79
Tom Spencer Avatar answered Nov 10 '22 08:11

Tom Spencer