Search code examples
node.jsmongodbdatetimemongoosecompose-db

Node.js Date Objects stored in MongoDB as "1970-01-01T00:00:00.001Z"


I have a Node.js application and I'm using Mongoose to interface with MongoDB on Compose.io. Here's some code that should store the current date and time in my database:

signup.Volunteer.find({_id : uniqueid.toObjectId()}, function(err, doc){
    var volunteer = doc[0];
    var date = new Date();
    console.log(date.toString());
    //volunteer.time_out is an array
    //defined in Volunteer Schema as: 'time_in : [Date]'
    volunteer.time_in = volunteer.time_in.push(date);
    volunteer.save(function(err){
        ...
    });
});
....

If I print these date objects to the console, I get the right date. BUT, when I store the object in my database, it's stored as "1970-01-01T00:00:00.001Z". Is there any idea why this would be happening?


Solution

  • The problem is that you're assigning the return value of volunteer.time_in.push back to volunteer.time_in. The return value is the new length of the array, not the array itself.

    So change that line to just:

    volunteer.time_in.push(date);