在mongodb中插入当前日期时间

20

我一直在使用Node.js的mongojs驱动程序将实际的日期时间对象插入到mongodb中时遇到了问题。有什么帮助吗?

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});

7
只需要插入一个 new Date() 就可以了吗? - Sammaye
1个回答

34

您不需要手动创建所有这些日期。

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

同时请注意,在Mongo 2.6中,除了许多其他功能之外,您还可以使用$currentDate,这可能很方便。


2
你如何确保 new Date() 与数据库的服务器时间同步?假设我想将值设置为大约60秒后,我如何确保像 date.setSeconds(date.getSeconds() + 60) 这样的操作会考虑到时区或不正确的服务器/客户端时间并存储正确的值? - Jespertheend

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接