Search code examples
node.jsmongodbmongoose-schema

MongoDB / Mongoose timestamps not updating


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.


Solution

  • Stumbled upon the same thing, figured out that if the property updatedAt is set on my object when I'm updating it with findOneAndUpdate() (or update()), it won't update it.

    In my case, solved it by making sure updatedAt isn't set before update:

    delete thing.updatedAt;
    
    Thing.findOneAndUpdate(
      { _id : thing._id },
      thing,
      function (err, result) {
       …
    

    Credit to Valeri Karpov for his answer on Github.