In my database collections, I want to update a 'lastChanged' field every time the record is updated with the current datetime. I want it to be in the same format as mongoose's default date like:
ISODate("2011-10-06T14: 01: 31.106Z")
Any words of wisdom?
Here's how you declare a path of type Date with a Mongoose schema: const mongoose = require('mongoose'); const userSchema = new mongoose. Schema({ name: String, // `lastActiveAt` is a date lastActiveAt: Date }); const User = mongoose. model('User', userSchema);
Timestamps save the current time of the document created and also when it was updated in form of a Date by turning it true. When set to true, the mongoose creates two fields as follows: createdAt: Date representing when the document was created. updatedAt: Date representing when this document was last updated.
Mongoose save with an existing document will not override the same object reference. Bookmark this question.
If you just want an ISO String use:
new Date().toISOString()
One way of accomplishing this is to use Mongoose Middleware and update the field pre-save.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//schema
var SomethingSchema = new Schema({
text: {type: String},
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now}
});
//middle ware in serial
SomethingSchema.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"
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