jack blank jack blank - 2 months ago 16x
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

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

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


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
when I want so why cant I use the
variable? it looks like it's a string so I don't know why the variable operator is not working.


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