22

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?

Community
  • 1
  • 1
wilsonpage
  • 17,341
  • 23
  • 103
  • 147

5 Answers5

28

If you just want an ISO String use:

new Date().toISOString()
greenimpala
  • 3,777
  • 3
  • 31
  • 39
17

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 and post are not called for update operations executed directly on the database, including Model.update,.findByIdAndUpdate,.findOneAndUpdate, .findOneAndRemove,and .findByIdAndRemove.order to utilize pre or post middleware, you should find() the document, and call the init, validate, save, or remove functions on the document. See explanation.

Update: See this question "add created_at and updated_at fields to mongoose schemas"

Community
  • 1
  • 1
Dave Jensen
  • 4,574
  • 1
  • 40
  • 45
11

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},
  }
)
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
0

The middleware function is a good approach, however, it should be

SomethingSchema.pre('save', function preSave(next){
  var something = this;
  something.updatedAt = Date.now();
  next();
});

Since something.updateAt is not a function.

0

I added updated: new Date to fix a similar problem. Here is how I used it.

update: (req, res) => {
        let userId = req.params.id;
        let userParams = {
            name: {
                first: req.body.first,
                last: req.body.last
            },
            email: req.body.email,
            password: req.body.password,
            updated: new Date
        };

        db.User.findOneAndUpdate(userId, { $set: userParams })
            .then(upUser => res.json(`Profile Updated for: ${upUser.fullName}`))
            .catch(err => res.status(422).json(err));
    }
Dharman
  • 30,962
  • 25
  • 85
  • 135