Alexander Mills
Alexander Mills

Reputation: 100080

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 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...)

Upvotes: 6

Views: 5402

Answers (1)

JLRishe
JLRishe

Reputation: 101700

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

Upvotes: 7

Related Questions