Compound Operations复合运算
On this page本页内容
Overview概述
Most database requests need to either read data out of a database or write data into a database. 大多数数据库请求需要从数据库中读取数据或将数据写入数据库。However, there are instances where you may need to read and write data in a single interaction.但是,在某些情况下,您可能需要在单个交互中读取和写入数据。
Compound operations combine read and write operations in a single atomic statement, so there's no chance of data changing in between a read and a subsequent write.复合操作将读取和写入操作组合在一个原子语句中,因此在读取和后续写入之间不可能发生数据更改。
If you execute each operation separately, another request may alter the data between the read and write operations. 如果分别执行每个操作,则另一个请求可能会在读取和写入操作之间更改数据。These data changes may not prevent your operation from succeeding, but they can make error handling more difficult. 这些数据更改可能不会阻止您的操作成功,但会使错误处理更加困难。When your application has to handle potential errors at any stage of the process, it can become brittle and difficult to test.当您的应用程序在过程的任何阶段都必须处理潜在的错误时,它可能会变得脆弱且难以测试。
Built-in Methods内置方法
The Node.js driver provides the following methods to perform compound operations:Node.js驱动程序提供了以下方法来执行复合操作:
These methods accept an optional 这些方法接受具有可配置排序和投影选项的可选options
object with configurable sort and projection options.options
对象。
includeResultMetadata
Option选项
Starting in version 5.7, you can set the 从5.7版开始,您可以在includeResultMetadata
setting in the options
object to specify the return type for each of these methods. options
对象中设置includeResultMetadata
设置,以指定这些方法中每个方法的返回类型。The setting defaults to 该设置默认为true
, which means the method returns a ModifyResult
type. true
,这意味着该方法返回ModifyResult
类型。If you set 如果将includeResultMetadata
to false
, the method returns the modified document.includeResultMetadata
设置为false
,则该方法将返回修改后的文档。
Suppose a collection contains the following document:假设一个集合包含以下文档:
{ _id: 1, x: "on" }
The following code shows the return type for 以下代码显示了findOneAndDelete()
operations when includeResultMetadata
is set to true
and false
:includeResultMetadata
设置为true
和false
时findOneAndDelete()
操作的返回类型:
// returns { _id: 1, x: 'on' }
await coll.findOneAndDelete({ x: "on" }, { includeResultMetadata: false });
// returns { lastErrorObject: { n: 1 }, value: { _id: 1, x: 'on' }, ok: 1, ... }
await coll.findOneAndDelete({ x: "on" }, { includeResultMetadata: true });
// no document matched, returns null
await coll.findOneAndDelete({ x: "off" }, { includeResultMetadata: false });
You can set the 您可以在returnDocument
setting in the options
object for the findOneAndUpdate()
and findOneAndDelete()
methods, which lets you specify if the method returns the pre-update or post-update version of the modified document.options
对象中为findOneAndUpdate()
和findOneAndDelete()
方法设置returnDocument
设置,这样可以指定该方法是返回修改后文档的更新前版本还是更新后版本。