乐闻世界logo
搜索文章和话题

How to add created at and updated at fields to mongoose schemas?

1个答案

1

When defining a schema in Mongoose, the created_at and updated_at fields are commonly used to track when records are created and last updated. To add these fields in Mongoose, you can utilize the built-in timestamps option, which automatically includes them in your schema. Here is an example of how to implement it in a Mongoose schema:

javascript
const mongoose = require('mongoose'); const Schema = mongoose.Schema; // Define schema const exampleSchema = new Schema({ // Other fields of the schema name: { type: String, required: true }, description: { type: String } // You don't need to explicitly define the created_at and updated_at fields }, { timestamps: true // This will automatically add created_at and updated_at fields }); // Create model const ExampleModel = mongoose.model('Example', exampleSchema); module.exports = ExampleModel;

In this example, setting timestamps to true instructs Mongoose to automatically add created_at and updated_at fields to each schema instance. When you create a new document, Mongoose automatically sets the values of created_at and updated_at fields to the current timestamp. When you update a document, only the updated_at field is updated to the latest timestamp.

By default, these fields are named created_at and updated_at. If you want to customize these field names, you can pass an object containing createdAt and updatedAt properties:

javascript
const exampleSchema = new Schema({ // Other fields of the schema name: { type: String, required: true }, description: { type: String } }, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } // Customize field names });

Using the timestamps option ensures that these fields are automatically handled during document creation or update, allowing you to easily track the history of documents without adding extra code.

2024年6月29日 12:07 回复

你的答案