网站搜索

javascript - MongoDB:添加或更新包含嵌套数组的项


我有一份包含以下数据的文档:

Chest: {
    ChestID: 400, // Chest ID is unique
    Items: [{
        ItemID: 200, //Item ID unique too
        ItemIndexes: ['aaa10', 'bbb20'] // indexes should not be repeated
    }]
}

我尝试去做这件事,但我找不到让它工作的办法:

public async appendItems(chestId: number, items: Array < ChestItem > ) {
    const tokensIds = items.map(item => item.tokenId)
    // bidimensional array [][]
    const tokenIndexes = items.map(item => item.indexesAsArray)

    await this.raw.updateOne({
        ChestID: chestId
    }, {
        $push: {
            "Items.$[item].token_indexes": {
                // in that bidimensional array there can be repeated indexes
                $each: tokenIndexes,
                position: "$"
            }
        }
    }, {
        arrayFilters: [{
            "item.token_id": {
                $in: tokensIds
            }
        }],
    })
}

所以我想做以下事情:

首先我必须找到箱子的ID,然后我必须找到物品的ID,然后如果物品ID存在,只需添加新的索引(不能有重复的索引),如果不存在则添加该物品。