Reputation: 764
I am using mongoose to store objects in mongodb, I record the createdAt date by using Date.now()
What I am finding is that the wrong time is being stored in the database. The difference is very sporadic and has been 7 days, 3 days and even 5 minutes off.
Just this morning I created an object at 8.00AM (GMT+10) AEST, yet the time in the database was 7 days earlier.
This is the database object:
{
"_id": "554bdfaf797cb8e02753e06f",
"description": "test d",
"createdBy": "testuser",
"key": "f1a593f4dd51e632388a1755e09a7b4dc0bc0e24ef8bcf5cf859ac759a45e8a6",
"__v": 0,
"files": [],
"createdAt": "2015-05-01T05:42:07.687Z"
}
I have seen this issue on both on my mac and win 7.
First noticed on mongodb version 2.6.3, just upgraded to 3.0.2, no change.
Update
I am setting the createdAt date within the schema like so:
var uploadSchema = new Schema({
createdAt: {
type: Date,
required: true,
default: Date.now()
},
My database and application are running on the same host.
gist here - https://gist.github.com/reecefenwick/1bcff85d18406b33e5cf
Upvotes: 10
Views: 3497
Reputation: 311835
What's going on is that you're calling Date.now()
at the time the schema is defined to set the default value for createdAt
, and then that value is being used for the default until the next time your app is restarted.
Instead, you want to set the default value to the Date.now
function itself so that it will be called each time a new doc is created:
var uploadSchema = new Schema({
createdAt: {
type: Date,
required: true,
default: Date.now
},
Upvotes: 21
Reputation: 59571
If you paste the object id into the website here:
http://steveridout.github.io/mongo-object-time/
You will see that this specific document was created today (2015-05-07T21:57:03.000Z
). The object id contains creation date information.
Where's the code for where you are creating the createdAt
entry? Is the database and your application code on separate servers? This could explain why mongo is creating the object id with a different date than createdAt
.
If they are on the same server, you should post the code that is creating the createAt
time string.
Upvotes: 0