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

I have a read-only API and I would like Mongoose to always have poor queries .

Can this be enabled by default at the schema or connection level?

+7
mongoose
source share
2 answers

The easiest way is to use the patch mongoose.Query class for the monkey to add a default default 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 a new mongoose.Query instance for each query, and the call to setOptions is part of the mongoose.Query construct.

By mongoose.Query class, you can turn the worst queries globally. Thus, you do not need to use all the mongoose methods ( find , findOne , findById , findOneAndUpdate , etc.).

mongoose uses the Query class for internal calls, such as padding. It passes the original Query parameters for each subquery, so there should be no problems, but be careful with this solution.

+13
source share

A crash can run something like this:

The current way to execute the request is:

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

Scenario using the Model find method:

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

New way to execute the request:

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

I have not tested this code, but if you previously tried to redefine library functions in JavaScript, you will easily understand where I get

+2
source share

All Articles