If I want my backend Node.js API to be generic, I would like to let clients determine for themselves if they want a 'lean' MongoDB query or a full query.
In order to just get back JSON (actually, POJSOs, not JSON), we use lean() like so:
Model.find(conditions).limit(count).lean().exec(function (err, items) {});
however, what if I wanted to conditionally call lean()?
if(isLean){
Model.find(conditions).limit(count).lean().exec(function (err, items) {});
else(){
Model.find(conditions).limit(count).exec(function (err, items) {});
}
this is not that big of a deal to have two different calls, but imagine if we had more than one conditional, not just isLean
, then we would have a factorial thing going on where we had many many calls, not just 2 different ones.
So I am wondering what is the best way to conditionally call lean()
- my only idea is to turn lean into a no-op if isLean
is false...
this would involve some monkey-patching TMK -
function leanSurrogate(isLean){
if(isLean){
return this.lean();
}
else{
return this;
}
}
anyone have something better?
(or perhaps the mongoose API already has this: lean(false)
, lean(true)
...and defaults to true...)
Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false. Use switch to select one of many blocks of code to be executed.
Yes you can use a fucntion as a condition for if, but that function should return a boolean value (or the value that can be converted to bool by implicit conversion) showing it's success or failure. Like return true if value is added or false if some error occured.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands. The expression consists of three operands: the condition, value if true and value if false. The evaluation of the condition should result in either true/false or a boolean value.
I think you're overthinking this. You don't have to restrict yourself to using one long series of method calls in one shot.
You can break it up where you need to, allowing you to avoid duplicating code:
var query = Model.find(conditions).limit(count);
if (isLean) {
query = query.lean();
}
query.exec(function (err, items) {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With