Mongoose - conditionally calling lean() in node.js

101 views
Skip to first unread message

al...@lectal.com

unread,
Oct 31, 2015, 3:19:37 PM10/31/15
to Mongoose Node.JS ODM
I am trying to determine how lean() works so that I can call it conditionally?

Here is my question on SO, if you could answer it there it would be best - 




here is the original question - please see SO link for better syntax highlighting -

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

Reply all
Reply to author
Forward
0 new messages