CreatedAt and updatedAt
In a data table structure, the creation time and update time are essential fields. Because the business logic involves data time filtering query, data traceability and other requirements. Therefore, developers need to manually record the creation time and update time.
The related documents
When Mongoose creates a Schema, it provides timestamps. This parameter will enable the creation time and update time automatically.
Schema Definition examples:
const Role = new Schema({
...
}, {
timestamps: true});Copy the code
The generated data is as follows:
{
"createdAt": "ISODate("2021-01-13T10:05:46.987Z")"."updatedAt": "ISODate("2021-01-13T10:05:46.987Z")",}Copy the code
By default, the generated fields are named createdAt and updatedAt, which you can customize by setting timestamps.
Custom time field name
Schema Definition examples:
const Role = new Schema({
...
}, {
timestamps: { createdAt: 'created'.updatedAt: 'updated'}});Copy the code
The generated data is as follows:
{
"created": "ISODate("2021-01-13T10:05:46.987Z")"."updated": "ISODate("2021-01-13T10:05:46.987Z")",}Copy the code
By default, the time format generated by Mongoose is UTC time, which is inconvenient to query data in this format. For example, for date range query, the time format can be fixed as string or timestamp number type
Modify the time format
Schema Definition examples:
const Role = new Schema({
...
created: {
type: number
},
updated: {
type: number
}, {
timestamps: { createdAt: 'created'.updatedAt: 'updated'}});Copy the code
The generated data is as follows:
{
"created" : 1610534416616."updated" : 1610534416616
}
Copy the code
The default time is millisecond accurate!
Modify the timestamp format
By default, Mongoose uses new Date() to get the current time. You can set the timestamps. CurrentTime option to override the format in which Mongoose gets the currentTime.
Schema Definition examples:
const Role = new Schema({
...
created: {
type: number
},
updated: {
type: number
},
{
timestamps: { currentTime: () = > Math.floor(Date.now() / 1000), createdAt: 'created'.updatedAt: 'updated'}}});Copy the code
The generated data is as follows:
{
"created": 1610536511."updated": 1610536511
}
Copy the code
Time to the second!
conclusion
Most businesses have a need to record when data was created and modified. The server will unify the time into the number (1610534696) format or string (2021-01-13) format, the query method is more convenient, query performance will be better!