Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting and Querying Date with MongoDB and Nodejs

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

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

jsonObj.last_updated = new Date(); 

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

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

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

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?

like image 238
jeh Avatar asked Jan 22 '14 15:01

jeh


People also ask

How does MongoDB store dates in node?

The best format to store date and time in MongoDB is native javascript Date() or ISO date format as it internally converts it into BSON native Date object.

How do I create a date in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.


2 Answers

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) { 

The MongoDB driver will transform it into ISODate:

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

Check these questions:

  • MongoDB + nodejs : how to query ISODate fields?
  • ISODate is not defined
like image 127
Ilan Frumer Avatar answered Oct 02 '22 12:10

Ilan Frumer


To clarify. What is important to know is that:

  • Yes, you have to pass a Javascript Date object.
  • Yes, it has to be ISODate friendly
  • Yes, from my experience getting this to work, you need to manipulate the date to ISO
  • Yes, working with dates is generally always a tedious process, and mongo is no exception

Here is a working snippet of code, where we do a little bit of date manipulation to ensure Mongo can handle it correctly. In this example, I am using mongoose module and want results for rows whose date attribute is less than (ie. before) the date given as myDate param.

var inputDate = new Date(myDate.toISOString()); MyModel.find({     'date': { $lte: inputDate } }) 
like image 21
arcseldon Avatar answered Oct 02 '22 12:10

arcseldon