In Mongoose, updating embedded documents (also known as sub-documents) typically follows these steps:
1. Locate the Main Document
First, identify the main document containing the embedded document, typically using its _id.
2. Update the Embedded Document
Once the main document is located, access and modify the fields of the embedded document using array indexing or a specific identifier.
3. Save the Changes
After updating the embedded document, save the main document to persist the changes.
Example:
Consider a User model with an embedded array of addresses documents. Each address document includes street and city fields.
javascriptconst mongoose = require('mongoose'); const Schema = mongoose.Schema; const addressSchema = new Schema({ street: String, city: String }); const userSchema = new Schema({ name: String, addresses: [addressSchema] }); const User = mongoose.model('User', userSchema);
To update a specific address for a user, follow these steps:
javascriptUser.findById(userId, (err, user) => { if (err) { console.log(err); return; } // Update the first address const address = user.addresses[0]; address.street = "New Street Name"; address.city = "New City"; // Save the update user.save((err) => { if (err) { console.log(err); } else { console.log('User address updated successfully'); } }); });
Alternative Method: Using findOneAndUpdate
If you prefer not to load the entire user document initially, use findOneAndUpdate with $set to directly update specific fields of the embedded document:
javascriptconst update = { $set: { 'addresses.0.street': 'New Street Name', 'addresses.0.city': 'New City' } }; User.findOneAndUpdate({_id: userId}, update, {new: true}, (err, user) => { if (err) { console.log(err); } else { console.log('User address updated successfully', user); } });
Here, addresses.0.street refers to updating the street field of the first element in the addresses array. The {new: true} option ensures the updated document is returned.
Summary
Updating embedded documents in Mongoose can be achieved by directly modifying the document and calling save, or by using findOneAndUpdate for more precise updates. The method chosen depends on your specific requirements, such as whether you need to process data before or after the update or perform validations.