Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Is there a way to default lean to true (always on)?

I have a read-only API that I'd like Mongoose to always have lean queries for.

Can I enable this either on a schema or connection level to be true by default?

like image 204
k00k Avatar asked Oct 04 '13 14:10

k00k


People also ask

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

What does lean () do in Mongoose?

The lean() function tells mongoose to not hydrate query results. In other words, the results of your queries will be the same plain JavaScript objects that you would get from using the Node. js MongoDB driver directly, with none of the mongoose magic.

Are Mongoose fields required by default?

It seems that the default value of the required attributes of each field in mongoose schema is false.


2 Answers

The easiest way is to monkey patch mongoose.Query class to add default lean option:

var __setOptions = mongoose.Query.prototype.setOptions;

mongoose.Query.prototype.setOptions = function(options, overwrite) {
  __setOptions.apply(this, arguments);
  if (this.options.lean == null) this.options.lean = true;
  return this;
};

Mongoose creates new instance of mongoose.Query for every query and setOptions call is a part of mongoose.Query construction.

By patching mongoose.Query class you'll be able to turn lean queries on globally. So you won't need to path all mongoose methods (find, findOne, findById, findOneAndUpdate, etc.).

Mongoose uses Query class for inner calls like populate. It passes original Query options to each sub-query, so there should be no problems, but be careful with this solution anyway.

like image 63
Leonid Beschastny Avatar answered Nov 15 '22 21:11

Leonid Beschastny


A hack-around could be performed something like this:

Current way of executing the query:

Model.find().lean().exec(function (err, docs) {
    docs[0] instanceof mongoose.Document // false
});

Fiddle with the Model's find method:

var findOriginal = Model.prototype.find;
Model.prototype.find = function() {
    return findOriginal.apply(this, arguments).lean();
}

New way of executing the query:

Model.find().exec(function (err, docs) {
    docs[0] instanceof mongoose.Document // false
});

I have not tested this code, but if you have tried to override library functionality in JavaScript before, you will easily grasp where I'm getting

like image 33
tomahaug Avatar answered Nov 15 '22 20:11

tomahaug