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?
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.
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.
mongoose. model() returns a Model ( It is a constructor, compiled from Schema definitions).
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.
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(); });
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