簡體   English   中英

在 mongodb 的 api 代碼中更新和第二級嵌套數組的元素

[英]Updating and element of a 2nd level nested array in api code for mongodb

我的 mongodb 數據庫包含一組用戶,每個用戶都有一系列商店,每個商店都有一系列產品。 這是我的收藏結構的簡化版本:

[
    {
        "_id": "60e66b70da2439232e330415",
        "name": "User1 Name",
        "shops": [
            {
                "_id": "60e7c9e2be0d8f03544a03b8",
                "shopName": "User1 Shop1 Name",
                "products": [
                    {
                        "_id": "60e9e9e8105d6021a2e91535",
                        "title": "User1 Shop1 Product1 Title"
                    },
                    {
                        "_id": "60e9f4a0105d6021a2e91536",
                        "title": "User1 Shop1 Product2 Title"
                    }
                ]
            },
            {
                "_id": "60e8e8c00f3986577cb968c9",
                "shopName": "User1 Shop2 Name",
                "products": [
                    {
                        "_id": "60e9f4fe105d6021a2e91537",
                        "title": "User1 Shop2 Product1 Title"
                    },
                    {
                        "_id": "60e9f515105d6021a2e91538",
                        "title": "User1 Shop2 Product2 Title"
                    }
                ]
            }
        ]
    },
    {
        "_id": "60e66b93da2439232e330416",
        "name": "User2 Name",
        "shops": [
            {
                "_id": "60e69698e76cad44e49e1fc8",
                "shopName": "User2 Shop1 Name",
                "products": [
                    {
                        "_id": "60e9f588105d6021a2e91539",
                        "title": "User2 Shop1 Product1 Title"
                    },
                    {
                        "_id": "60e9f59c105d6021a2e9153a",
                        "title": "User2 Shop1 Product2 Title"
                    }
                ]
            },
            {
                "_id": "60e902b441e9df63c7fbcb49",
                "shopName": "User2 Shop2 Name",
                "products": [
                    {
                        "_id": "60e9f5c9105d6021a2e9153b",
                        "title": "User2 Shop2 Product1 Title"
                    },
                    {
                        "_id": "60e9f5de105d6021a2e9153c",
                        "title": "User2 Shop2 Product2 Title"
                    }
                ]
            }
        ]
    }
]

我有一個像.../api/products/60e9f5de105d6021a2e9153c這樣的 api 端點。 此端點包含一個參數,即 productId。 我有以下兩個代碼來更新我的 mongodb 集合中的產品數據,但我的 ode 不起作用,也不會更新預期的元素。

我的端點代碼:

app.put("/api/products/:productID", (req, res) => {
    let productID = req.params.productID;
    let productData = req.body;
    
    myData.updateProductByProductId(productData, productID)
    .then(confMsg => res.json({"message": confMsg}))
    .catch(err => res.json({"message": err}));

});

我的數據服務代碼:

updateProductByProductId: function(productData, productID){
            return new Promise((resolve, reject)=>{
                User.updateOne(
                    { "shops.products._id" : productID},
                    { $set: { "shops.products.$":  productData } }
                ).exec().then(()=>{
                    resolve(`product ${productID} successfully updated.`)
                }).catch(err=>{
                    reject(err);
                });
            });
        }

上面的代碼返回這個錯誤:

{
    "message": {
        "driver": true,
        "name": "MongoError",
        "index": 0,
        "code": 28
    }
}

我還嘗試使用{ "shops.products._id" : mongoose.Types.ObjectId(productID)}而不是{ "shops.products._id" : productID}並得到了相同的結果。

非常感謝您抽出寶貴的時間和善意的建議。

我正在為您的問題添加 mongodb 查詢。 您可以使用貓鼬。

await db1.updateOne(
        {
            "shops": {
                "$elemMatch": {
                    "products._id": productID
                }
            }
        },
        {
            "$set": {
                "shops.$.products.$[inner].name": "new name",
                "shops.$.products.$[inner].description": 'description',
                "shops.$.products.$[inner].oName": 'oName',
                "shops.$.products.$[inner].type": 'type'
            }
        },
        {
            "arrayFilters": [
                { "inner._id": productID }
            ]
        }, (err, result) => {
            if (err) {
                console.log('Error updating service: ' + err);
                res.send({ 'error': 'An error has occurred' });
            } else {
                // console.log('' + result + ' document(s) updated');
                res.send(result);
            }
        })

否則要更新整個產品詳細信息,您可以使用以下內容

let newDetails = {
        _id: productID,
        name: "newName11", Description: "Description11"
    }

await db1.updateOne(
        {
            "shops": {
                "$elemMatch": {
                    "products._id": productID
                }
            }
        },
        {
            "$set": {
                "shops.$.products.$[inner]": newDetails
            }
        },
        {
            "arrayFilters": [
                { "inner._id": productID }
            ]
        }, (err, result) => {
            if (err) {
                console.log('Error updating service: ' + err);
                res.send({ 'error': 'An error has occurred' });
            } else {
                // console.log('' + result + ' document(s) updated');
                res.send(result);
            }
        })

您可以使用 arrayFilter 過濾數組元素

User.update(
 { "shops.products._id": mongoose.Types.ObjectId("60e9f5de105d6021a2e9153c") },
 { $set: { "shops.$.products.$[elem].title": "new title" } },
 { arrayFilters:[{"elem._id":mongoose.Types.ObjectId("60e9f5de105d6021a2e9153c")}]}
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM