试图将“$ gt”放入查找中。 {[CastError:对于路径“createdAt”中的值“[object Object]”,“转换为日期失败”]

时间:2016-08-11 22:32:20

标签: javascript node.js mongodb express mongoose

我有这段代码:Reviews.find({createdAt : {"$lt" : app.locals.lastDate}})我想动态地将$lt更改为$gt

app.post("/scroll", function(req, res){
    console.log("req.body...", req.body);
    var sortCreate = req.body.older == true ? "createdAt" : "-createdAt"
    var greaterOrLess = req.body.older == true ? "$gt" : "$lt";
    greaterOrLess = greaterOrLess.toString()
    console.log("greaterOrLess;;;", greaterOrLess)
    console.log("inside scroll app.locals.lastDate", app.locals.lastDate)
    Reviews.find({createdAt : {"$lt" : app.locals.lastDate}})
    .limit(10)
    .sort(sortCreate).exec()

问题是当我更改Reviews.find({createdAt : {"$lt" : app.locals.lastDate}})

Reviews.find({createdAt : {greaterOrLess : app.locals.lastDate}})

我收到错误:

{ [CastError: Cast to date failed for value "[object Object]" at path "createdAt
"]
  message: 'Cast to date failed for value "[object Object]" at path "createdAt"'
,
  name: 'CastError',
  kind: 'date',
  value: { greaterOrLess: Sun Aug 07 2016 19:25:48 GMT-0700 (Pacific Daylight Ti
me) },
  path: 'createdAt',
  reason: undefined }

此部分:console.log("greaterOrLess;;;", greaterOrLess)打印出$gt$lt,因为我不能使用greaterOrLess变量?它看起来像是一个字符串,所以我不知道为什么变量运算符不起作用。

1 个答案:

答案 0 :(得分:0)

您无法在对象中拥有动态键。相反,你可以这样做:

var greaterOrLess = req.body.older == true ? {"$gt" : app.locals.lastDate} : {"$lt" : app.locals.lastDate};
Reviews.find({createdAt : greaterOrLess})