How to create a date field with default value,the default value should be current timestamps whenever the insertion happened in the collection.
10 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.
-
1Appreciate the note that, we need to pass function object and not invoke it right away! Nov 23, 2022 at 13:40
Use _id to get the timestamp.
For this particular purpose you don't really need to create an explicit field for saving timestamps. The object id i.e. "_id"
, that mongo creates by default can be used to serve the purpose thus, saving you an additional redundant space. I'm assuming that you are using node.js so you can do something like the following to get the time of particular document creation:
let ObjectId = require('mongodb').ObjectID
let docObjID = new ObjectId(<Your document _id>)
console.log(docObjID.getTimestamp())
And, if you are using something like mongoose, do it like this:
let mongoose = require('mongoose')
let docObjID = mongoose.Types.ObjectId(<Your document _id>)
console.log(docObjID.getTimestamp())
Read more about "_id" here.
-
1If you are using it for TTL purpose, _id will not work. You need to explicitly create a timestamp field. docs.mongodb.com/manual/core/index-ttl/#restrictions Aug 26, 2020 at 12:52
When Creating Document, timestamps is one of few configurable options which can be passed to the constructor or set directly.
const exampleSchema = new Schema({...}, { timestamps: true });
After that, mongoose assigns createdAt and updatedAt fields to your schema, the type assigned is Date.
You would simply do this while inserting... for current timestamp
.
collection.insert({ "date": datetime.now() }
-
Thanks thalaiva.. This query we can handle to run every insertion through query i agree that.Is there any way to handle this date time insertion through configure like RDBMS concept the below query @columnName datetime default CURRENT_TIMESTAMP Apr 11, 2016 at 13:47
-
1@JagadeesanG: you would need mongoose if you are going with a schema... mongodb is as such schemaless. mongoosejs.com/docs/2.7.x/docs/schematypes.html Apr 11, 2016 at 13:50
Let's consider the user schema in which we are using created date, we can use the mongoose schema and pass the default value as Date.now
var UserSchema = new Schema({
name: {type: String, trim: true},
created: {type: Date, default: Date.now}
});
If we want to save timetamp instead of number then use Number isntead of number like that
var UserSchema = new Schema({
name: {type: String, trim: true},
created: {type: Number, default: Date.now}
});
Note:- When we use Date.now() in the default parameter then this will only set the Date once to the value of when your Schema got created, so you'll find the dates same as the that in the other document. It's better to use Date.now instead of Date.now().
I just wish to point out that in case you want the timestamp to be stored in the form of an integer instead of a date format, you can do this:
{
timestamp: { type: Number, default: Date.now},
...
}
Here's a command that doesn't set a default, but it inserts an object with the current timestamp:
db.foo.insert({date: new ISODate()});
These have the same effect:
db.foo.insert({date: ISODate()});
db.foo.insert({date: new Date()});
Be aware that Date()
without new
would be different - it doesn't return an ISODate
object, but a string.
Also, these use the client's time, not the server's time, which may be different (since the time setting is never 100% precise).
Thanks friends .. I found another way to get timestamp from _id field. objectid.gettimestamp() from this we can get it time stamp.
This is a little old, however I fount when using the Date.now() method, it doesn't get the current date and time, it gets stuck on the time that you started your node process running. Therefore all timestamps will be defaulted to the Date.now() of when you started your server. One way I worked around this was to do the following:
ExampleSchema.pre('save', function (next) {
const instanceOfSchema = this;
if(!instanceOfSchema.created_at){
instanceOfSchema.created_at = Date.now();
}
instanceOfSchema.updated_at = Date.now();
next();
})
mongodb-csharp
driver or the shell?