gre*_*ala 17
如果您只想使用ISO String:
new Date().toISOString()
Run Code Online (Sandbox Code Playgroud)
Dav*_*sen 12
实现此目的的一种方法是使用Mongoose Middleware并更新字段预保存.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//schema
var SomethingSchema = new Schema({
text: {type: String},
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now}
});
//middle ware in serial
SomethingSchema.pre('save', function preSave(next){
var something = this;
something.updatedAt(Date.now());
next();
});
Run Code Online (Sandbox Code Playgroud)
但是,似乎并不总是调用中间件:
关于findAndUpdate()的注释
pre并且post不要求直接对数据库进行更新执行操作,包括Model.update,.findByIdAndUpdate,.findOneAndUpdate,.findOneAndRemove,和.findByIdAndRemove.order利用pre或post中间件,你应该find()文档,并调用init,validate,save,或remove在文档的功能.见解释.
更新:请参阅此问题" 将created_at和updated_at字段添加到mongoose架构 "
在几天内,Mongo将宣布新的2.6版本(目前你可以下载实验性的2.5.x版本).在许多其他功能中,你可以使用$ currentDate来完成你想要的东西:
db.users.update(
<criteria>,
{
$currentDate: { yourField: true},
}
)
Run Code Online (Sandbox Code Playgroud)