jack blank jack blank - 3 months ago 25
Javascript Question

trying to put "$gt" into a find. { [CastError: Cast to date failed for value "[object Object]" at path "createdAt "]

I have this piece of code :

Reviews.find({createdAt : {"$lt" : app.locals.lastDate}})
I wanted to change the
$lt
to
$gt
dynamically.

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()


the problem is when I change
Reviews.find({createdAt : {"$lt" : app.locals.lastDate}})


to

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


I get error:

{ [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 }


this part:
console.log("greaterOrLess;;;", greaterOrLess)
prints out
$gt
or
$lt
when I want so why cant I use the
greaterOrLess
variable? it looks like it's a string so I don't know why the variable operator is not working.

Answer

You cannot have dynamic keys in an object. Instead you can do something like that:

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