MongoDB / Mongoose时间戳不更新

架构:

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日,但对文档的任何新的编辑不会更新时间戳。

感觉像我在这里错过了一些非常愚蠢的东西。

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

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

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

方法-2

在架构中添加了createdDateupdatedDate Datetypes,并使用架构插件更新这些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都是在同一时间创build的,当使用mongoose将新文档input到数据库中时,所以您检查updatedAt是否未定义是不合逻辑的,因为在创build新文档时两者都具有相同的值。

每当使用mongoose更新函数或findByIdAndUpdate或findOneAndUpdate时,updatedAt的值将自动更新。使用mongochef或robomongo等Mongodb客户端直接检查updatedAt的值。

你正在比较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(); }); 

试试这个,它应该工作