MongoDB + Node.js:无法正确插入日期 [英] MongoDB + Node.js: unable to insert date properly

查看:66
本文介绍了MongoDB + Node.js:无法正确插入日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 node-mongoskin 来连接这两者.一切正常,直到我查询了一些日期"字段,我认为该字段应作为javascript的Date对象返回.但是结果的类型是字符串,这对我来说很奇怪并且不方便.

I′ve been using node-mongoskin to connect this two. Everything was ok until I queried some "date" field which I think should be returned as javascript′s Date object. But result′s type was string, which is odd (for me) and inconvenient.

插入看起来像这样:

var doc = {
  date: new Date(),
  info: 'Some info'
}
db.users.insert( doc, {safe: true}, function(err, res) {
  ...
});

上面的结果是(没有_id字段):

And result of above is (without _id field):

{ "date" : "Mon Oct 24 2011 18:00:57 GMT+0400 (MSK)", "info": "Some info" }

但是,使用MongoDB Shell插入可以很好地工作,除了字段类型为ISODate

However, inserting with MongoDB Shell works just fine, except type of field is ISODate

> db.things.insert({ date: new Date() }); db.things.find();
{ "_id" : ObjectId("4eae9f2a34067b92db8deb40"), "date" : ISODate("2011-10-31T13:14:18.947Z") }

因此,问题是:如何插入文档作为Date对象来查询日期字段?我想要在数据库服务器端设置字段.我只是发送诸如null字段之类的内容,而db-server使用默认的mongo机制为我设置这些内容.

So, the question is: how should I insert documents to query date fields as Date object? What I want is setting fields on database-server-side. I just send something like null-fields, and db-server setting those for me using default mongo′s mechanisms.

插入时间戳(例如原生MongoDB时间戳)也是一个问题,但没什么大不了的.

Inserting timestamps (as native MongoDB timestamp) is also a problem, but it′s not such a big deal.

PS:没有运气通过mongoskin和 mongodb-native 文档.

PS: No luck going through mongoskin and mongodb-native docs.

推荐答案

这可能是我的代码或mongo驱动程序中的一些错误.现在,以下工作正常:

It was probably some bug in my code or the mongo driver. Now, the following works just fine:

db.collection.insert({d: new Date()});

此处描述了时间戳支持: http://mongodb.github.com/node-mongodb-native/api-bson-generated/timestamp.html .

Timestamps support described here: http://mongodb.github.com/node-mongodb-native/api-bson-generated/timestamp.html.

这篇关于MongoDB + Node.js:无法正确插入日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆