Docs Menu

Docs HomeNode.js

Compound Operations

On this page

  • Overview
  • Built-in Methods

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.

The Node.js driver provides the following methods to perform compound operations:

  • findOneAndDelete()

  • findOneAndUpdate()

  • findOneAndReplace()

These methods accept an optional options object with configurable sort and projection options.

Note

includeResultMetadata Option

Starting in version 5.7, you can set the includeResultMetadata setting in the options object to specify the return type for each of these methods.

Starting in version 6.0, this setting defaults to false, which means that each method returns the matched document. If no document is matched, each method returns null. If you set includeResultMetadata to true, the method returns a ModifyResult type that contains the found document and additional metadata.

Suppose a collection contains only the following document:

{ _id: 1, x: "on" }

The following code shows how the value of the includeResultMetadata option changes the return type of the findOneAndDelete() method:

// default behavior
// returns { _id: 1, x: 'on' }
await coll.findOneAndDelete({ x: "on" });
// 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" });

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.

←  Specify a QueryPromises →
Share Feedback
© 2023 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.