简体   繁体   中英

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) {
     res.send(err);
  }

   res.json(reason);

});

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM