使用MongoDB和Nodej插入和查询日期 [英] Inserting and Querying Date with MongoDB and Nodejs

查看:709
本文介绍了使用MongoDB和Nodej插入和查询日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助,在mongodb和nodejs中找到一个记录。

I need some help finding a record by date in mongodb and nodejs.

我将这个日期添加到抓取脚本中的json对象中,如下所示:

I add the date to the json object in a scraping script as follows:

jsonObj.last_updated = new Date();

此对象插入到mongodb中。我可以看到如下:

This object is inserted into mongodb. I can see it as follows:

 "last_updated" : "2014-01-22T14:56:59.301Z"

然后在我的nodejs脚本中,我做了一个findOne():

Then in my nodejs script I do a findOne():

 var jObj = JSON.parse(line.toString());

 collection.findOne(jObj,function(err, doc) {
   if (doc){
     console.log(doc._id);
   } else  {
     console.log('not found');
   }
 });

找不到该对象。如果我从对象中删除last_updated字段,那么它确实是问题所在。

The object is not found. If I remove the last_updated field from the object it is found so it is definitely where the problem is.

如果我将该字段隔离如下:

If I isolate the field as follows:

collection.findOne({last_updated: '2014-01-22T14:56:59.301Z'},function(err, doc) {
  if (doc){
    console.log(doc._id);
  } else  {
    console.log('not found');
  }
});

没有任何东西回来。我在做什么错?

Nothing comes back either. What am I doing wrong please?

谢谢。

推荐答案

你需要传递日期对象而不是日期字符串。

You need to pass a date object and not a date string.

collection.findOne({last_updated: new Date('2014-01-22T14:56:59.301Z')},function(err, doc) {

MongoDB驱动程序将其转换为 ISODate

The MongoDB driver will transform it into ISODate:

{ 
   "_id" : ObjectId("52dfe0c469631792dba51770"), 
   "last_updated" : ISODate('2014-01-22T14:56:59.301Z') 
}

检查这些问题:

  • MongoDB + nodejs : How to query ISODate fields?
  • ISODate is not defined

这篇关于使用MongoDB和Nodej插入和查询日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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