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

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

问题描述

我需要一些帮助,以便在 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 插入和查询日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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