Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting the current datetime in mongodb

Tags:

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});
like image 412
David Avatar asked Oct 26 '13 21:10

David


People also ask

How is datetime stored in MongoDB?

MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.

Does MongoDB add a timestamp?

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 ...


1 Answers

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.

like image 82
Salvador Dali Avatar answered Sep 24 '22 19:09

Salvador Dali