How to create a date field with default value,the default value should be current timestamps whenever the insertion happened in the collection.
Date now = new Date(); BasicDBObject timeNow = new BasicDBObject("date", now); example. insert(timeNow);
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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With