Sim*_*ole 9 mongodb node.js mongoose-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();
});
Run Code Online (Sandbox Code Playgroud)
此代码最近正在运行 - 对于特定实例,updatedAt将在8月24日出现,但对文档的任何新编辑都不会更新时间戳.
感觉我在这里错过了一些非常愚蠢的东西.
可以尝试修改您的架构,例如:
var schema =new Schema({..},
{ timestamps: { createdAt: 'createdDate',updatedAt: 'updatedDate' }
});
Run Code Online (Sandbox Code Playgroud)
对于此架构,timestmps 将在save()
、update()
和上更新findOneAndUpdate()
。所以没必要schema.virtual('updated')...
进程 2
添加createdDate
和updatedDate
使用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);
Run Code Online (Sandbox Code Playgroud)
在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);
};
Run Code Online (Sandbox Code Playgroud)
偶然发现了同样的事情,发现如果updatedAt
当我使用findOneAndUpdate()
(或update()
) 更新它时在我的对象上设置了该属性,它就不会更新它。
就我而言,通过确保updatedAt
更新前未设置来解决此问题:
delete thing.updatedAt;\n\nThing.findOneAndUpdate(\n { _id : thing._id },\n thing,\n function (err, result) {\n \xe2\x80\xa6\n
Run Code Online (Sandbox Code Playgroud)\n\n感谢 Valeri Karpov 在 Github 上的回答。
\n 归档时间: |
|
查看次数: |
5350 次 |
最近记录: |