0

I know that this question might be beginner level but I haven't find anything yet. I would like to update an array of objects with mongoose. I am interested in updating one object from the users array according to the index. Usually one user is getting changed at a time.

Here is my schema:

 _id: Schema.Types.ObjectId,
name: { type: String, required: true },
gm: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
},
users: [],

I want to update an object in the users array which is like this:

{
    id:"5bcb7c7ff9c5c01b9482d244",
    gm:"5bcb7c7ff9c5c01b9482d246",
    name:"room 1"
    users: [
        {
            id:"5bcb7c7ff9c5c01b9482d243",
            stats:{
                power:10,
                mobility: 5,
                vitality: 20
            },
            bag:{itemSlot1: "Knife",itemSlot2:"Sword" }
        },
        {
            id:"5bcb7c7ff9c5c01b9482d241",
            stats:{
                power:10,
                mobility: 5,
                vitality: 20
            },
            bag:{itemSlot1: "Knife",itemSlot2:"Sword" }
    ]
}

I want to perform a patch or a post request to update one user each time from the user array. i am getting the id of the user from req.body to match it with my db.

My request is like this:

I would like to update based on a request like this:

data = {
  stats={
    power:"10",
    vitality:"20"
   }
}

Thanks in advance, Cheers

1 Answer 1

1

You can do an update like this:

YourSchema.update({
  'users.id': '5bcb7c7ff9c5c01b9482d243'
}, {
  $set: {
    'users.$.stats': data.stats
  }
})

Which would update the first user with id 5bcb7c7ff9c5c01b9482d243 power stats to 20

This is using the update with the $ positional operator to update the element in the array.

Just have it set up in your post/patch request.

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

6 Comments

Sure I updated the answer. Just set with the data.stats then.
and what if i get a bag object as well and some key pairs are missing from the request?
That is something you can do in your request before the update call. You can default values if the data does not have what you want etc. I am just providing the request to mongoose not the entire request handler.
can i make a dynamic $set though and update only the values i get?
You could simply compose your set object and just add the props you want to update like this: { 'users.$.stats.power': data.stats.power, 'users.$.stats.other': data.stats.other } based on what you have in data.stats
|

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.