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.

Jiří Rejman
  • 85
  • 1
  • 1
  • 9
  • Possible duplicate of [MongoDB: How do I update a single subelement in an array, referenced by the index within the array?](https://stackoverflow.com/questions/11372065/mongodb-how-do-i-update-a-single-subelement-in-an-array-referenced-by-the-inde) – Ashh Apr 13 '19 at 08:00

1 Answers1

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

konuralpt
  • 263
  • 2
  • 11
  • 1
    `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 – Jiří Rejman Apr 13 '19 at 08:57
  • SOLVED - The problem was using fixed value instead of $ in $set part of solution – Jiří Rejman Apr 13 '19 at 09:06