Inserting the current datetime in mongodb

David picture David · Oct 26, 2013 · Viewed 41.2k times · Source

I have been having trouble inserting an actual datetime object in mongodb using the mongojs driver for nodejs. Any help?

var currentdate = new Date(); 
var datetime = currentdate.getDate() + "/"
+ (currentdate.getMonth()+1)  + "/" 
+ currentdate.getFullYear() + " @ "  
+ currentdate.getHours() + ":"  
+ currentdate.getMinutes() + ":" 
+ currentdate.getSeconds();

db.test.update({
    conversation: conv
},{ 
    $push:{ messages: {
        message: message,
        pseudo: name,
        current_date: datetime
    }}
},{upsert: true});

Answer

Salvador Dali picture Salvador Dali · Oct 27, 2013

You do not need to do all this manual date creation.

db.test.update({
    conversation: conv
}, { 
    $push:{ messages: {
        message: message,
        pseudo: name,
        current_date: new Date()
    } }
}, {
    upsert: true
});

would do the job.

Also keep in mind, that in Mongo 2.6 among many other features you can use $currentDate which might be handy.