Code Ratchet Code Ratchet - 1 year ago 35
Javascript Question

Apply filter if value exists otherwise ignore - mongoose

I have the following field within my collection:

"intent" : [
"Find a job",
"Advertise a job"

What I'm trying to do is basically filter results on that field.

So if the end user passes in

"Find a job",

I would then return all documents that have the intent
Find a job
this is my query so far:

var _intent = req.body.intent;

Reason.find({ intent: { $in: _intent }}, function (err, reason) {
if (err) {



Now this works when I specify a value for
as I'm using the
-Logical Query Operator however when I do not specify a value for
it fails to return any documents, so what I'm asking is, is there a way I can say if
has a value then filter on it, otherwise if it doesn't then do not apply the filter?

Answer Source

Why not set the query object dynamically?

var query = {};

if ( req.body.hasOwnProperty('intent') )
    query.intent = { "$in": req.body.intent };

Reason.find(query, function(err, reason) {


Or even

if ( req.body.intent.length > 0 )

Which ever case of logic suits. It's all just JavaScript after-all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download