乐闻世界logo
搜索文章和话题

How to update subdocument with findOneAndUpdate in Mongoose?

1个答案

1

In Mongoose, the findOneAndUpdate method is used to update data within MongoDB documents. When updating nested documents (i.e., documents embedded within a document), it is crucial to carefully specify the path for the target document.

Suppose we have a model named User that includes an array field called addresses, where each array item is an object containing street, city, and zip code. Our goal is to update a specific address for a particular user.

Step 1: Define the Model

First, we need to define the model:

javascript
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const addressSchema = new Schema({ street: String, city: String, zipCode: String }); const userSchema = new Schema({ name: String, addresses: [addressSchema] }); const User = mongoose.model('User', userSchema);

Step 2: Using findOneAndUpdate to Update Nested Documents

To update data in nested documents, we must use MongoDB's dot notation to specify the field path for the update. Assume we know the _id of the address to modify.

javascript
const userId = 'some_user_id'; const addressId = 'some_address_id'; const newStreet = 'new_street_name'; const newCity = 'new_city_name'; const newZipCode = 'new_zip_code'; User.findOneAndUpdate( { _id: userId, 'addresses._id': addressId }, { $set: { 'addresses.$.street': newStreet, 'addresses.$.city': newCity, 'addresses.$.zipCode': newZipCode } }, { new: true } // Returns the updated document ) .then(updatedDocument => { console.log('Update successful:', updatedDocument); }) .catch(error => { console.error('Update failed:', error); });

In this example:

  • We use the first parameter of findOneAndUpdate to locate the correct user document while ensuring the addresses array contains an address with the matching _id.
  • The $set operator updates specific fields within the nested document.
  • 'addresses.$' serves as MongoDB's position placeholder, indicating the first element that satisfies the array query condition.
  • The { new: true } option guarantees that the updated document is returned.

By employing this approach, we can precisely update the nested document within the array without impacting other nested documents.

2024年6月29日 12:07 回复

你的答案