MongoDB / Mongoose timestamps not updating

Simon Poole picture Simon Poole · Sep 14, 2016 · Viewed 8.6k times · Source

Schema:

var schema = new Schema({...}, {
    timestamps: true,
    id: false,
    toJSON: {
        virtuals: true,
    },
    toObject: {
        virtual: true,
    }
});
schema.virtual('updated').get(function () {
    if(typeof this.updatedAt === "undefined" && typeof this.createdAt === "undefined") return "";
    var updated = (typeof this.updatedAt === "undefined") ? this.createdAt : this.updatedAt;
    return "Updated "+moment(updated).fromNow();
});

This code was working recently - updatedAt for a particular instance comes up as August 24th, however any new edits to the document doesn't update the timestamp.

Feels like I'm missing something very silly here.

Answer

Shaishab Roy picture Shaishab Roy · Sep 26, 2016

Can try by modify your schema like:

var schema =new Schema({..}, 
           { timestamps: { createdAt: 'createdDate',updatedAt: 'updatedDate' } 
});

for this schema timestmps will update on save(), update() and findOneAndUpdate(). so no need schema.virtual('updated')...

Process-2

added createdDate and updatedDate with Date type in your schema and update these date fields using schema plugin.

like:

var mongoose = require('mongoose'),
    Schema   = mongoose.Schema,
    SchemaPlugin = require('../helpers/schemaPlugin');
  var schema =new Schema({..},
    createdDate: {
      type: Date,
      default: Date.now
    },
    updatedDate: {
      type: Date,
      default: Date.now
    }
  });

  schema.plugin(SchemaPlugin);

in schemaPlugin.js file:

module.exports = function(schema) {

  var updateTimestemps = function(next){
    var self = this;


    if(!self.createdAt) {
      self.createdDate = new Date();
      //or self.update({},{ $set: { createdDate : new Date(), updatedDate: new Date() } });
    } else {
      self.updatedDate= new Date();
      //or self.update({},{ $set: {updatedDate: new Date() } });
    }
    next();
  };

  schema.
    pre('save', updateTimestemps ).
    pre('update', updateTimestemps ).
    pre('findOneAndUpdate', updateTimestemps);
};