MongoDB / Mongoose 时间戳未更新

MongoDB / Mongoose timestamps not updating

架构:

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();
});

此代码最近工作的 - 特定实例的 updatedAt 在 8 月 24 日出现,但是对文档的任何新编辑不会 更新时间戳。

感觉我在这里遗漏了一些非常愚蠢的东西。

您正在比较 objectString,这就是为什么条件总是 false

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();
});

试试这个,应该有用

可以尝试修改您的架构,例如:

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

对于此模式,timestmps 将在 save()update()findOneAndUpdate() 上更新。所以不需要 schema.virtual('updated')...

进程 2

添加了 createdDateupdatedDate 以及 Date 输入您的模式并使用 模式插件 更新这些日期字段。

喜欢:

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);

schemaPlugin.js 文件中:

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);
};

updatedAt 和 createdAt 都是在使用猫鼬将新文档输入数据库时​​同时创建的,因此检查 updatedAt 是否未定义是不合逻辑的,因为在创建新文档时两者将具有相同的值。

每当您使用 mongoose 更新函数或 findByIdAndUpdate 或 findOneAndUpdate 时,updatedAt 的值将被更新 automatically.Use Mongodb 像 mongochef 或 robomongo 这样的客户端直接检查 updatedAt 的值。

偶然发现了同样的事情,我发现当我用 findOneAndUpdate()(或 update() 更新对象时,如果 属性 updatedAt ), 它不会更新它。

就我而言,通过确保 updatedAt 未在更新前设置来解决它:

delete thing.updatedAt;

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

Credit to Valeri Karpov for his answer on Github.