How to update a nested object in using mongoose

Member

by addison , in category: MySQL , a month ago

How to update a nested object in using mongoose

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , a month ago

@addison 

To update a nested object in MongoDB using Mongoose, you can use the findOneAndUpdate method provided by Mongoose.


Here is an example of how you can update a nested object in a Mongoose model:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const mongoose = require('mongoose');

// Create a Mongoose schema
const userSchema = new mongoose.Schema({
    name: String,
    address: {
        street: String,
        city: String,
        state: String
    }
});

// Create a Mongoose model
const User = mongoose.model('User', userSchema);

// Update a nested object in the database
User.findOneAndUpdate(
    { name: 'John' },
    { $set: { 'address.city': 'New York' }},
    { new: true }, // Return the modified document rather than the original
    (err, user) => {
        if (err) {
            console.log(err);
        } else {
            console.log(user);
        }
    }
);


In this example, we are updating the city field of the address object for a user with the name 'John'. The $set operator is used to update the nested object. The new: true option tells Mongoose to return the modified document.


You can customize the update object according to your specific needs by using other Mongoose query operators such as $push, $pull, $inc, etc. to update nested objects in MongoDB using Mongoose.