我试图将对象中的值增加1,但我似乎无法弄清楚。我有一个猫鼬模式设置如下:
const userSchema = new Schema({
_id: Schema.Types.ObjectId,
userId: String,
items: Object
});
存储的数据如下:
items: {
"1234": 1,
"5678": 4
}
其中1234
、5678
为物品id,1
、4
为用户拥有该物品的数量。作为一个例子,我需要将"1234": 1
增加1,以返回"1234": 2
,并保持"5678" : 4
不变。我试过了:
let newItem = "1234";
let userProfile = await User.findOneAndUpdate({
userId: userID
}, {
$inc: {
items: {
newItem: 1
}
}
});
返回错误:The field 'items' must be an array but is of type object
.
我也试过了:
$inc: {
"items": {
newItem: 1
}
}
返回:Cannot increment with non-numeric argument: {items: { newItem: 1 }}
和:
$inc: {
`items.${newItem}`: 1
}
返回
`items.${newItem}`: 1
^^^^^^^^^
SyntaxError: Unexpected template string
明白了。要在keyname中使用变量,请将模板包装在[]
中$inc: {
[`items.${newItem}`]: 1
}