猫鼬:有没有办法默认默认为true(始终启用)? [英] Mongoose: Is there a way to default lean to true (always on)?

查看:106
本文介绍了猫鼬:有没有办法默认默认为true(始终启用)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个只读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方法(findfindOnefindByIdfindOneAndUpdate等)进行路径设置.

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

MongooseQuery类用于内部填充(如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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆