Optional Mongoose Search Query Parameters?

I have the following situation. I need to build a mongoose request based on certain arguments, if any.

those. if an object like this is transferred

{ player: "nickname", action: "capture" } 

the following search is performed:

 Entry.find({ player: obj.player, action: obj.action }). exec(function(err, res){ console.log(res); }); 

If I need to exclude an β€œaction” from the search, if the action is not in the object, what should I do? Using a ternary operator like action: (obj.action) ? obj.action:null action: (obj.action) ? obj.action:null does not work, nor does searching for records in the database, where action is null .

+4
source share
2 answers

Programmatically create a request object:

 var query = { player: 'player' }; if (obj.action) { query.action = obj.action; } Entry.find(query).exec(function(err, res){ console.log(res); }); 
+13
source

If someone meets the same question, here is how I solved it:

 var query = { player: 'player' }; Entry.find({ player: query.player, action: (query.action) ? query.action:/.*/ }). exec(function(err, res){ console.log(res); }); 
+2
source

All Articles