55

I am trying to get results from mongodb using nodejs/mongoose.

var dateStr = new Date(year,month,day,0,0,0);
var nextDate = new Date(year,month,day,23,59,59);

GPSData.find({"createdAt" : { $gte : new ISODate(dateStr), $lte:  new ISODate(nextDate) }}, function(err, data) {
  if(err)
    console.log(err); 
});

Error: ISODate is not defined

coure2011
  • 40,286
  • 83
  • 216
  • 349

6 Answers6

84

Note that ISODate is a part of MongoDB and is not available in your case. You should be using Date instead and the MongoDB drivers(e.g. the Mongoose ORM that you are currently using) will take care of the type conversion between Date and ISODate behind the scene.

qiao
  • 17,941
  • 6
  • 57
  • 46
  • 13
    It doesn't though. It creates a string. – Evan Zamir Jun 15 '13 at 17:44
  • 2
    The answer is correct. More detailed answer containing an example: http://stackoverflow.com/a/21286896/275183 – h-kippo Feb 27 '14 at 13:46
  • MongoDB will parse and store your Date Instance as ISODate("ISOstring"). But when you call said date again it will be returned as a Date Instance, I didn't want to believe it until I tested it myself. – WouldBeNerd Mar 24 '16 at 14:56
  • 1
    @EvanZamir you have to set type as 'datetime' in your model file. Driver will care about conversion by itself. – 1nstinct Aug 02 '16 at 10:58
21

In my case, I was converting a query with ISODates

let dateString = "2014-01-22T14:56:59.301Z";

$gte : ISODate( dateString )

in node.js is

$gte : new Date( dateString )
hestellezg
  • 3,309
  • 3
  • 33
  • 37
4

Convert date to MongoDB ISODate format in JavaScript using Moment JS

MongoDB uses ISODate as their primary date type. If you want to insert a date object into a MongoDB collection, you can use the Date() shell method.

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.
  • new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
  • new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
  • new Date() specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.

If you are writing code in JavaScript and if you want to pass a JavaScript date object and use it with MongoDB client, the first thing you do is convert JavaScript date to MongoDB date format (ISODate). Here’s how you do it.

    var today = moment(new Date()).format('YYYY-MM-DD[T00:00:00.000Z]');
    console.log("Next day -- " + (reqDate.getDate() + 1))
    var d = new Date();
    d.setDate(reqDate.getDate() + 1);
    var tomorrow = moment(d).format('YYYY-MM-DD[T00:00:00.000Z]');

You can pass today and tomorrow object to MongoDB queries with new Date() shell method.

  MongoClient.connect(con, function (err, db) {
    if (err) throw err
    db.collection('orders').find({ "order_id": store_id, "orderDate": {     
       "$gte": new Date(today), "$lt": new Date(tomorrow)}
     }).toArray(function (err, result) {
        console.log(result);
        if (err) throw err
          res.send(result);
    })
  })
Farrukh Malik
  • 746
  • 9
  • 13
3

Instead of ISO use "new Date" node js will take care of ISO itself, no need to write ISO just simply use "new Date"

Rahul Bhat
  • 65
  • 7
2

You can simply use as follow to convert dates in ISO string :

GPSData.find({"createdAt" : { $gte : new Date(year,month,day,0,0,0).toISOString(), $lte:  new Date(year,month,day,23,59,59).toISOString() }}, function(err, data) {
  if(err)
    console.log(err); 
});
Jitendra
  • 3,135
  • 2
  • 26
  • 42
-1
 if (req.params.sDate && req.params.eDate) {
      query["createdAt"] = {
        $gte:  new Date("2020-01-25").toISOString(),
        $lte:    new Date("2020-09-25").toISOString()
      };
    }

    console.log("query", query, req.params.limit, req.params.skip);
    domain.Payment.find(query)
      .limit(req.params.limit)
      .skip(req.params.skip)
      .sort({ createdAt: -1 })
      .exec((err, list) => {
        console.log("err", err);

        if (err || !list) {
          callback(err, null);
        } else {
Shashwat Gupta
  • 5,071
  • 41
  • 33