20

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});
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
David
  • 679
  • 1
  • 9
  • 22

1 Answers1

34

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.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • 2
    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? – Jespertheend Aug 11 '21 at 12:13