0
db.test.find({"date":{$gte:"2017-04-11",$lt:"2017-04-13"}},function(err,doc){
      console.log("date function called");
    res.json(doc);

    console.log(doc);
});

code works fine in mongodb and output,but in nodejs the output is empty array.

2
  • First, use console.log(err) to see if there is an error Commented Apr 1, 2017 at 11:00
  • 1
    you should use date as object not as string Commented Apr 1, 2017 at 11:03

1 Answer 1

1

Collections can be queried with find. The result for the query is actually a cursor object. This can be used directly or converted to an array. Making queries with find()

cursor.toArray(function(err, docs){}) converts the cursor object into an array of all the matching records. Probably the most convenient way to retrieve results but be careful with large datasets as every record is loaded into memory. toArray

The mongo shell wraps objects of Date type with the ISODate helper; however, the objects remain of type Date. Return Date

var collection = db.collection('test');
collection.find({ "date": { $gte: new Date("2017-04-11"), $lt: new Date("2017-04-13") } })
  .toArray(function (err, doc) {
    console.log("date function called");
    if (err) {
      console.error(err);
    } else {
      console.log(doc);
      res.json(doc);
    }
  });
Sign up to request clarification or add additional context in comments.

5 Comments

i used the above code but it gives ReferenceError: ISODate is not defined
i got a output like this : server running on port 9000 date function called []
@VijaykumarVijay use new Date, not ISODate
@VijaykumarVijay Is your collection named test?
i used new Date and collection name is test itself. It works fine in mongoshell but in nodejs i got like this ,date function called [] empty array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.