猫鼬:有没有办法默认默认为true(始终启用)? [英] Mongoose: Is there a way to default lean to true (always on)?
问题描述
我有一个只读API,我希望Mongoose始终具有精益查询 .
I have a read-only API that I'd like Mongoose to always have lean queries for.
是否可以在模式或连接级别将其默认设置为true?
Can I enable this either on a schema or connection level to be true by default?
推荐答案
最简单的方法是使用猴子补丁mongoose.Query
类添加默认的精简选项:
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.Query
的新实例,而setOptions
调用是mongoose.Query
构造的一部分.
Mongoose creates new instance of mongoose.Query
for every query and setOptions
call is a part of mongoose.Query
construction.
通过修补mongoose.Query
类,您将能够全局打开精益查询.因此,您无需对所有mongoose
方法(find
,findOne
,findById
,findOneAndUpdate
等)进行路径设置.
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
将Query
类用于内部填充(如populate).它将原始的Query
选项传递给每个子查询,因此应该没有问题,但是无论如何都要小心使用此解决方案.
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.
这篇关于猫鼬:有没有办法默认默认为true(始终启用)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!