0

I have this mongoose schema

{
    id: mongoose.Schema.Types.ObjectId,
    name: String,
    initialMailSended: Boolean,
    email: String,
    users: [{
        id: mongoose.Schema.Types.ObjectId,
        name: String,
        surname: String,
        email: String,
        signedUp: Boolean,
        company: String,
        email: String,
        attending: String,
        accomod: String,
        program: String,
        food: String,
        other: String,
        allFood: String,
        form: [{
            name: String,
            value: String,
        }]
    }]
}

What i need to do is write a mongoose query which find this object by id and in this object find user and update it. I tried various queries but didn't find any which would work.

1

1 Answer 1

1

For your question, you can update your user like this

db.getCollection('collection').findOneAndUpdate(
    {
      _id:ObjectId("5cb19dbc85fdcb7868400107"),       // collection id
     'users._id':ObjectId("5cb19dbc85fdcb7868400185") // user id inside collection
    },

    {$set: {'users.$.name': 'new value'}}            // set name field
)

also see this question Updating a Nested Array with MongoDB

Sign up to request clarification or add additional context in comments.

2 Comments

Actions.find({ _id: actionId, 'users._id': userId }, (err, data) => { //console.log(data[0].users); console.log('data', data); }) this solution return data with all objects in array
SOLVED - The problem was using fixed value instead of $ in $set part of solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.