注意
Stable API 功能需要 MongoDB Server 5.0 或更高版本。
Overview
在本指南中,您可以了解如何在连接到stable API MongoDB部署时指定 兼容性。
Stable API功能会强制服务器以与您指定的API版本兼容的行为来运行操作。 使用 Stable API可确保服务器响应一致,并为应用程序提供长期的API稳定性。
以下部分介绍如何为MongoDB客户端启用和自定义 Stable API 。有关 Stable API的更多信息,包括其支持的命令列表,请参阅MongoDB Server手册中的 Stable API 。
启用stable API
要启用Stable API ,请在创建 Mongo::Client
实例时将指定 Stable API版本的哈希传递给可选的 server_api
参数。
以下代码示例展示了如何指定stable API版本 1:
client = Mongo::Client.new(uri, server_api: { version: '1' })
创建具有指定API版本的 Client
实例后,使用客户端运行的所有命令都将使用指定版本。 如果必须使用多个版本的 Stable API运行命令,请创建新的 Client
。
配置stable API
下表描述了您可以通过在 server_api
哈希中指定选项来设立的 Stable API选项。您可以使用这些选项来自定义 Stable API的行为。
选项名称 | 说明 |
---|---|
strict | Optional. When true , if you call a command that isn't part of
the declared API version, the driver raises an exception.Default: false |
deprecation_errors | Optional. When true , if you call a command that is deprecated in the
declared API version, the driver raises an exception.Default: false |
以下代码示例展示了如何在 ServerApi
实例上设立这两个选项:
client = Mongo::Client.new(uri, server_api: { version: '1', strict: true, deprecation_errors: true })
故障排除
以下部分介绍了使用 Stable API时可能遇到的常见问题。
服务器上无法识别的字段“apiVersion”
如果您指定API版本并连接到不支持Stable API的MongoDB服务器,则Ruby驾驶员会引发此异常。确保您要连接到运行MongoDB Server v5.0 或更高版本的部署。
已提供 apiStrict:true,但命令计数不在 API 版本中
如果您的 Client
运行的操作不属于您指定的 Stable API版本,则Ruby驾驶员会引发此异常。要避免此错误,请使用指定 Stable API版本支持的替代操作,或在构造 ServerApi
对象时将 strict
选项设立为 false
。
API 文档
有关将 Stable API与Ruby驾驶员结合使用的更多信息,请参阅以下API文档: