我有这段代码: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
变量?它看起来像是一个字符串,所以我不知道为什么变量运算符不起作用。
答案 0 :(得分:0)
您无法在对象中拥有动态键。相反,你可以这样做:
var greaterOrLess = req.body.older == true ? {"$gt" : app.locals.lastDate} : {"$lt" : app.locals.lastDate};
Reviews.find({createdAt : greaterOrLess})