所以我試圖在 discord.js 中撰寫一個機器人,你基本上在庫存中有物品,當我使用一個物品時,它的耐用性會下降。我正在使用 MongoDB Atlas 來存盤所有資料。庫存結構如下:
user: {
id: 'user-id',
name: 'user-name',
inventory: [
{
name: 'item',
durability: 5
,
{
name: 'another-item',
durability: 20
}
]
}
所以我只是想找到一種方法,基本上只是減少物品的耐用性,而不更新庫存陣列中的任何其他物品,但我無法找到一種方法來做到這一點。
uj5u.com熱心網友回復:
您可以使用arrayFilters僅更新您想要的值。
您也可以使用$inc來增加值(在這種情況下增加 -1,即減少)
db.collection.update({
"id": "user-id"
},
{
"$inc": {
"inventory.$[element].durability": -1
}
},
{
"arrayFilters": [
{
"element.name": "item" //here use the name of the object you want to update
}
]
})
這里的例子
uj5u.com熱心網友回復:
我認為它有效,但彈出一個新錯誤:MongooseError: Callback must be a function, got [object Object]. 我在 Google 中檢查了這個錯誤,人們說這是由于 this => MongooseError: Callback must be a function, got [object Object]的語法錯誤造成的。我的代碼是這樣的:
const updatedUserData = await profileSchema.findOneAndUpdate({
userId: interaction.user.id
}, {
"$inc": {
"inventory.$[element].number": 1
}
}, {
"arrayFilters": [
{
"element.id": "stone"
}
]
}, {
upsert: true
})
但是當我像這樣將 arrayFilters 移動到 $inc 物件中時:
const updatedUserData = await profileSchema.findOneAndUpdate({
userId: interaction.user.id
}, {
"$inc": {
"inventory.$[element].number": 1
},
"arrayFilters": [
{
"element.id": "stone"
}
]
}, {
upsert: true
})
一個新的錯誤來了 MongoServerError: No array filter found for identifier 'element' in path 'inventory.$[element].number'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406697.html
標籤:
