JavaScript - conditionally call a function

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 request or a full request.

To simply return JSON (in fact, POJSOs, not JSON), we use lean () as follows:

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) {});

}

it is not so much as to have two different calls, but imagine if we had more than one conditional, and not just isLeanthen we would have a factorial thing in which we had many calls, and not just 2 different.

So I'm wondering how best to conditionally invoke lean()- my only idea is to turn lean into no-op if isLeanfalse ...

this will be due to some changes in TMK -

function leanSurrogate(isLean){
  if(isLean){
    return this.lean();
  }
  else{
   return this;
 }
}

- - ?

(, , API- mongoose : lean(false), lean(true)... - true...)

+4
1

, . .

, , :

var query = Model.find(conditions).limit(count);

if (isLean) {
    query = query.lean();
}

query.exec(function (err, items) {});
+5

Source: https://habr.com/ru/post/1613984/


All Articles