查找具有字段日期的MongoDB记录< Date.now()

时间:2017-02-01 20:20:32

标签: node.js mongodb mongoose mongoose-schema

所以我将Robomongo应用程序链接到MongoDB。我跑的时候:

db.getCollection('bookings').find({"date" : { $lte : new Date("<YYYY-mm-ddTHH:MM:ssZ>")}})

我找到的预订记录的日期字段在当前日期+时间之前。

然而,当我尝试使用Mongoose在我的Node应用程序中执行类似的操作时,我收到以下错误:

{ MongooseError: Cast to date failed for value "Invalid Date" at path "date"
    at CastError (/Users/jack/Sites/view-bookings/node_modules/mongoose/lib/error/cast.js:26:11)
    at SchemaDate.cast (/Users/jack/Sites/view-bookings/node_modules/mongoose/lib/schema/date.js:221:13)
    at SchemaDate.handleSingle (/Users/jack/Sites/view-bookings/node_modules/mongoose/lib/schema/date.js:256:15)
    at SchemaDate.castForQuery (/Users/jack/Sites/view-bookings/node_modules/mongoose/lib/schema/date.js:289:18)

这是我目前的代码:

router.get('/past', function(req, res) {
  //retrieve all bookings from Monogo
  mongoose.model('Booking').find({"date" : { $lte : new Date("<YYYY-mm-ddTHH:MM:ssZ>")}}, function (err, bookings) {
        if (err) {
            return console.error(err);
        } else {
            //respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
            res.format({
                //HTML response will render the index.jade file in the views/bookings folder. We are also setting "bookings" to be an accessible variable in our jade view
              html: function(){
                  res.render('bookings/index', {
                        title: 'All my Bookings',
                        "bookings" : bookings
                    });
              },
              //JSON response will show all bookings in JSON format
              json: function(){
                  res.json(bookings);
              }
          });
        }
  });
});

首次使用Mongoose如果这很容易就道歉。

0 个答案:

没有答案
相关问题