如何增加一个对象的值,MongoDB



我试图将对象中的值增加1,但我似乎无法弄清楚。我有一个猫鼬模式设置如下:

const userSchema = new Schema({
_id: Schema.Types.ObjectId,
userId: String,
items: Object
});

存储的数据如下:

items: {
"1234": 1,
"5678": 4
}

其中12345678为物品id,14为用户拥有该物品的数量。作为一个例子,我需要将"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 
}

相关内容

最新更新