Mongoose timestamps are supported by the schema. Timestamps save the current time of the document created and also when it was updated in form of a Date by turning it true. When set to true, the mongoose creates two fields as follows:
The two fields are created when the database was first created and then updated by the queries save(), updateOne(), updateMany(), findOneAndUpdate(), update(), replaceOne(), or bulkWrite(). Syntax: Create schema with a timestamp as follows:
Creating Application and installing Modules: We will create a schema with the timestamps and then print the different timestamps that are createdAt and updatedAt by updating the details of a student. Step 1: Create a folder and initialize it: npm init Step 2: Install mongoose in the project. npm i mongoose Project Structure: The project structure is as follows:
Example: Create a file called index.js. Inside the index.js, connect to MongoDB. Here the MongoDB Compass is used. Now first create the Student schema and then its model. Now create a new document and save it. Print the document timestamps and then update the document after a time delay and then again print the timestamp details. index.js
npm i mongoose2 npm i mongoose3 npm i mongoose4 npm i mongoose5 npm i mongoose6 npm i mongoose7 npm i mongoose8 npm i mongoose9 npm i mongoose6 node index.js1 node index.js2 node index.js3 node index.js4 npm i mongoose9 node index.js4 node index.js7 npm i mongoose8 node index.js9
node index.js4 "mongoose" 2npm i mongoose4 "mongoose" 4npm i mongoose6 "mongoose" 6npm i mongoose6 "mongoose" 8node index.js4 ); 0node index.js4 ); 2npm i mongoose6 ); 4); 5); 6); 7); 8npm i mongoose6 ); 4 1 2npm i mongoose6 ); 4 5 6node index.js4 ); 0
node index.js4 // Database connection 3npm i mongoose6 // Database connection 5// Database connection 6 npm i mongoose9 npm i mongoose6 // Database connection 9npm i mongoose6 mongoose.connect( 1npm i mongoose4 mongoose.connect( 3npm i mongoose8 node index.js9 node index.js4 ); node index.js4 ); 4); 5); 6); 7); 8node index.js4 ); 4 1 2node index.js4 ); 4 5 6
npm i mongoose04 node index.js4 npm i mongoose06 // Database connection 6npm i mongoose08 node index.js4 npm i mongoose10 npm i mongoose11 npm i mongoose12 npm i mongoose6 npm i mongoose14 node index.js4 npm i mongoose16
npm i mongoose19 Step 4: Run the code using the following command: node index.js Output: The output in the command line is as follows. The output shows that the document is updated after 3 seconds.
Output of MongoDB: The following field will now reflect in the database also, as shown in the image below: |