node.js 如何在每次保存时使用 Mongoose 架构中的当前日期更新属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7675549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:39:36  来源:igfitidea点击:

How do I update a property with the current date in a Mongoose schema on every save?

node.jsmongodbmongoosenosql

提问by wilsonpage

In my database collections, I want to update a 'lastChanged' field every time the record is updated with the current datetime. I want it to be in the same format as mongoose's default date like:

在我的数据库集合中,每次使用当前日期时间更新记录时,我都想更新“lastChanged”字段。我希望它与猫鼬的默认日期格式相同,例如:

ISODate("2011-10-06T14: 01: 31.106Z")

ISODate("2011-10-06T14: 01: 31.106Z")

Any words of wisdom?

有什么智慧的话吗?

回答by greenimpala

If you just want an ISO String use:

如果您只想要 ISO 字符串,请使用:

new Date().toISOString()

回答by Dave Jensen

One way of accomplishing this is to use Mongoose Middlewareand update the field pre-save.

实现此目的的一种方法是使用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();
});

It seems, however, that the middleware is not always invoked:

然而,中间件似乎并不总是被调用:

Notes on findAndUpdate()

preand postare not called for update operations executed directly on the database, including Model.update,.findByIdAndUpdate,.findOneAndUpdate, .findOneAndRemove,and .findByIdAndRemove.order to utilize preor postmiddleware, you should find()the document, and call the init, validate, save, or removefunctions on the document. See explanation.

findAndUpdate() 的注意事项

pre并且post不调用直接在数据库上执行的更新操作,包括Model.update, .findByIdAndUpdate, .findOneAndUpdate, .findOneAndRemove, 和.findByIdAndRemove.orderprepost中间件,您应该find()使用文档,并调用文档上的initvalidatesave、 或remove函数。见说明

Update:See this question "add created_at and updated_at fields to mongoose schemas"

更新:请参阅此问题“将 created_at 和 updated_at 字段添加到猫鼬模式

回答by Salvador Dali

In a few days Mongo is going to announce new 2.6 version (currently you can download experimental 2.5.x version). Among many other featuresyou can use $currentDatewhich is going to do exactly the thing you want:

几天后,Mongo 将发布新的 2.6 版本(目前您可以下载实验 2.5.x 版本)。在许多其他功能中,您可以使用$currentDate来完成您想要的事情:

db.users.update( 
  <criteria>,
  {
     $currentDate: { yourField: true},
  }
)