ค้นหาเว็บไซต์

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
            }
        }],
    })
}

ดังนั้นฉันจึงต้องการทำสิ่งต่อไปนี้:

ก่อนอื่นฉันต้องหาหมายเลขตู้เก็บของก่อน จากนั้นฉันต้องหาหมายเลขไอเท็ม จากนั้นถ้าหมายเลขไอเท็มมีอยู่แล้ว ให้เพิ่มดัชนีใหม่ (จะมีดัชนีซ้ำไม่เกิน 1 รายการ) ถ้าไม่มี ให้เพิ่มไอเท็มนั้น