johnymachine johnymachine - 2 months ago 14
Node.js Question

How to make object for mongoose query?

Is there way to build complete object for mongoose to use as query? When making route for search I need to pass many query parameters and sanitize them in express middleware. From those I would like to build query object.

I ended up with something like this:

Inside midleware:

res.locals.filter = {
query: ...,
projection: ...,
sort: ...,
limit: ....,
}


inside router:

User.find(res.locals.filter.query)
.sort(res.locals.filter.sort)
.limit(res.locals.filter.limit)
.exec()


Is there any way to format my filter so I can pass it all at once? Found some examples but nothing seem to work for me...

In other word do something like:

User.query(filter)

Answer

As it was pointed out by JohnnyHK, the style of find call with object fields like $query and $orderBy was only supported in the shell (and is now deprecated) so there isn't any built-in support.