简体   繁体   中英

Update an array of objects mongoose

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

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.

You should retrieve the id of the user using req.params but since you retrieve it from the body I'll base my answer on that:

app.put('/api/users/:user_id', function(req, res) {
    var id = req.body.id;
    var newUser = req.body.user;
    User.findById(id, function (err, user) {
        if (err) return handleError(err);

        user.set(newUser);
        user.save(function (err, updatedUser) {
            if (err) return handleError(err);
            res.send(updatedUser);
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM