How do I update a property with the current date in a Mongoose schema on every save?
One way of accomplishing this is to use Mongoose Middleware and update the field pre-save.
var mongoose = require('mongoose');var Schema = mongoose.Schema;//schemavar SomethingSchema = new Schema({ text: {type: String}, createdAt: {type: Date, default: Date.now}, updatedAt: {type: Date, default: Date.now}});//middle ware in serialSomethingSchema.pre('save', function preSave(next){ var something = this; something.updatedAt(Date.now()); next();});
It seems, however, that the middleware is not always invoked:
Notes on findAndUpdate()
pre
andpost
are not called for update operations executed directly on the database, includingModel.update
,.findByIdAndUpdate
,.findOneAndUpdate
,.findOneAndRemove
,and.findByIdAndRemove
.order to utilizepre
orpost
middleware, you shouldfind()
the document, and call theinit
,validate
,save
, orremove
functions on the document. See explanation.
Update: See this question "add created_at and updated_at fields to mongoose schemas"
In a few days Mongo is going to announce new 2.6 version (currently you can download experimental 2.5.x version). Among many other features you can use $currentDate which is going to do exactly the thing you want:
db.users.update( <criteria>, { $currentDate: { yourField: true}, })