如何自动更新Mongodb中的Upsert上的时间戳

如果我有一个密钥expires的架构, 每次文档更新时,我怎样才能得到该键的值来自动更新? 这可能会更复杂,但是,我upsert所以这个值将需要设置在初始insert ,然后更新每个upsert

所以,当文档被insert

 { expires: *an hour from the insert* } 

当它update (通过upsert ):

 { expires: *an hour from the update* } 

如果MongoDB内置了这个function的话,我在使用Mongoose。如果Mongodb不支持它,也不会Mongoose,我只需要计算expires:并更新值,但是在Mongodb中自动完成这个操作会很好!

事实上,它不会真的需要insert ; 因为我可以检查expires为空,并从_id提取时间。

一如既往,任何帮助非常感谢!

Mongoose中间件不会触发update调用,所以您需要自己动手:

 var expires = new Date(); expires.setHours(expires.getHours() + 1); MyModel.update({...}, {$set: {expires: expires, ...}}, {upsert: true}, callback); 

此外,我不知道你的用例,但是你也应该看看Mongo内置的支持,如果这是你想要做的,那么从集合中过期的数据。 看到这里 。

Mongoose的最新版本允许在创build新模型时传递{ timestamps: true }作为选项。 此function将自动设置updatedAtupdatedAt 。 这里是文档 。