Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create a Date field with default value as the current timestamp in MongoDb?

How to create a date field with default value,the default value should be current timestamps whenever the insertion happened in the collection.

like image 531
Jagadeesan G Avatar asked Apr 11 '16 13:04

Jagadeesan G


People also ask

How do I create a date in MongoDB?

Date now = new Date(); BasicDBObject timeNow = new BasicDBObject("date", now); example. insert(timeNow);

Does MongoDB have timestamp?

Making sure that all your applications create and update MongoDB timestamps is going to be the hardest part of this process; MongoDB has no automatic timestamp support, so every one of your applications is going to have to make sure they do one of two things when working with the database: write a createdAt field, or ...


1 Answers

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},    ...  } 

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.

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

like image 90
Joschua Schneider Avatar answered Oct 23 '22 05:10

Joschua Schneider