Inserting the current datetime in mongodb
Asked Answered
I

1

21

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});
Indonesia answered 26/10, 2013 at 21:55 Comment(1)
just insert a new Date()?Unbreathed
D
35

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.

Dott answered 26/10, 2013 at 22:1 Comment(1)
How can you be sure the new Date() is synced with the server time of the database? Let's say I want to set the value roughly 60 seconds into the future. How can I be sure something like date.setSeconds(date.getSeconds() + 60) will store the correct value while taking time zones or an incorrect server/client time into account?Bustos

© 2022 - 2024 — McMap. All rights reserved.