且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在MongoDb中使用默认值创建一个Date字段作为当前时间戳?

更新时间:2023-01-08 09:34:45

那很简单! 例如,当您使用Mongoose时,可以将函数作为默认值传递. 然后,Mongoose每次插入都会调用该函数.

Thats pretty simple! When you're using Mongoose for example, you can pass functions as a default value. Mongoose then calls the function for every insertion.

因此,在您的架构中,您将执行以下操作:

So in your Schema you would do something like:

 {
   timestamp: { type: Date, default: Date.now},
   ...
 }

请记住仅传递函数对象本身Date.now而不传递函数调用Date.now()的值,因为这只会将Date一次设置为创建架构时的值.

Remember to only pass the function object itself Date.now and not the value of the function call Date.now()as this will only set the Date once to the value of when your Schema got created.

此解决方案适用于Mongoose& Node.Js,我希望这是您的用例,因为您没有更精确地指定它.

This solution applies to Mongoose & Node.Js and I hope that is your usecase because you did not specify that more precisely.