在mongodb中插入当前日期时间

Dav*_*vid 17 mongodb node.js mongojs

我一直无法使用mongojs驱动程序为nodejs在mongodb中插入实际的datetime对象.有帮助吗?

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});
Run Code Online (Sandbox Code Playgroud)

Sal*_*ali 29

您无需执行所有此手动日期创建.

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

会做的.

还要记住,在Mongo 2.6和许多其他功能中你可以使用$ currentDate,这可能很方便.

  • 如何确保“new Date()”与数据库的服务器时间同步?假设我想将该值设置为未来大约 60 秒。我如何确定像“date.setSeconds(date.getSeconds() + 60)”这样的东西会存储正确的值,同时考虑时区或不正确的服务器/客户端时间? (2认同)