[英]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
. 我想用
mongoose
更新一系列对象。 I am interested in updating one object from the users array according to the index. 我有兴趣根据索引从users数组更新一个对象。 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. 我想执行
patch
或post
请求,以每次从用户数组中更新一个用户。 i am getting the id of the user from req.body
to match it with my db. 我从
req.body
获取用户的ID,以使其与我的数据库匹配。
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
这会将ID为
5bcb7c7ff9c5c01b9482d243
的第一个用户的power
更新为20
This is using the update
with the $
positional operator to update the element in the array. 这是通过
$
位置运算符使用update
来更新数组中的元素。
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: 您应该使用
req.params
检索用户的id
,但是由于您是从正文中检索用户的id
,因此我将req.params
基础进行回答:
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);
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.