在 mongodb 的 api 代码中更新和第二级嵌套数组的元素 [英] Updating and element of a 2nd level nested array in api code for mongodb
问题描述
我的 mongodb 数据库包含一组用户,每个用户都有一系列商店,每个商店都有一系列产品.这是我的收藏结构的简化版本:
<预><代码>[{_id":60e66b70da2439232e330415",名称":用户 1 名称",商店":[{_id":60e7c9e2be0d8f03544a03b8","shopName": "User1 Shop1 Name",产品":[{_id":60e9e9e8105d6021a2e91535",title":User1 Shop1 Product1 Title"},{_id":60e9f4a0105d6021a2e91536",title":User1 Shop1 Product2 Title"}]},{_id":60e8e8c00f3986577cb968c9",商店名称":用户 1 商店 2 名称",产品":[{_id":60e9f4fe105d6021a2e91537",title":User1 Shop2 Product1 Title"},{_id":60e9f515105d6021a2e91538",title":User1 Shop2 Product2 Title"}]}]},{_id":60e66b93da2439232e330416",名称":用户 2 名称",商店":[{_id":60e69698e76cad44e49e1fc8",shopName":User2 Shop1 名称",产品":[{_id":60e9f588105d6021a2e91539",title":User2 Shop1 Product1 Title"},{_id":60e9f59c105d6021a2e9153a",title":User2 Shop1 Product2 Title"}]},{_id":60e902b441e9df63c7fbcb49",shopName":User2 Shop2 名称",产品":[{_id":60e9f5c9105d6021a2e9153b",title":User2 Shop2 Product1 Title"},{_id":60e9f5de105d6021a2e9153c",title":User2 Shop2 Product2 Title"}]}]}]我有一个 api 端点,如 .../api/products/60e9f5de105d6021a2e9153c
.此端点包含一个参数,即 productId.我有以下两个代码来更新我的 mongodb 集合中的产品数据,但我的 ode 不起作用并且不会更新预期的元素.
我的端点代码:
app.put("/api/products/:productID", (req, res) => {让 productID = req.params.productID;让 productData = req.body;myData.updateProductByProductId(productData, productID).then(confMsg => res.json({message": confMsg})).catch(err => res.json({message": err}));});
我的数据服务代码:
updateProductByProductId: function(productData, productID){返回新的承诺((解决,拒绝)=>{用户.updateOne({ "shops.products._id";: 产品 ID},{ $set: { "shops.products.$": productData } }).exec().then(()=>{解决(`产品 ${productID} 成功更新.`)}).catch(err=>{拒绝(错误);});});}
以上代码返回此错误:
<代码>{消息":{司机":真的,名称":MongoError",索引":0,代码":28}}
我也尝试使用 { "shops.products._id";: mongoose.Types.ObjectId(productID)}
而不是 { "shops.products._id";: productID}
并得到相同的结果.
非常感谢您抽出宝贵的时间和善意的建议.
我正在为您的问题添加 mongodb 查询.你也可以使用猫鼬.
await db1.updateOne({商店":{$elemMatch":{products._id":产品ID}}},{$set":{shops.$.products.$[inner].name":新名称",shops.$.products.$[inner].description": 'description',shops.$.products.$[inner].oName": 'oName',shops.$.products.$[inner].type":'类型'}},{数组过滤器":[{ "inner._id": productID }]}, (错误,结果) =>{如果(错误){console.log('更新服务出错:' + err);res.send({ 'error': '发生错误' });} 别的 {//console.log('' + result + '文档更新');res.send(结果);}})
否则要更新整个产品详细信息,您可以使用以下内容
let newDetails = {_id:产品ID,名称:newName11",描述:Description11";}等待 db1.updateOne({商店":{$elemMatch":{products._id":产品ID}}},{$set":{shops.$.products.$[inner]":newDetails}},{数组过滤器":[{ "inner._id": productID }]}, (错误,结果) =>{如果(错误){console.log('更新服务出错:' + err);res.send({ 'error': '发生错误' });} 别的 {//console.log('' + result + '文档更新');res.send(结果);}})
My mongodb database includes a collection of users and each user has an array of shops and each shop has an array of products. Here is a simplified version of my collection structure:
[
{
"_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"
}
]
}
]
}
]
I have an api endpoint like .../api/products/60e9f5de105d6021a2e9153c
. This endpoint includes a parameter which is a productId. I have the following two codes to update the product data from my mongodb collection, but my ode won't work and won't update the intended element.
My endpoint code:
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}));
});
My DataService code:
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);
});
});
}
The above code returns this error:
{
"message": {
"driver": true,
"name": "MongoError",
"index": 0,
"code": 28
}
}
I also tried using { "shops.products._id" : mongoose.Types.ObjectId(productID)}
instead of { "shops.products._id" : productID}
and got the same result.
Thank you very much in advance for your time and kind advice.
I am adding the mongodb query for your question. You can use mongoose for the same.
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);
}
})
otherwise to update the whole product details you can use the following
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);
}
})
这篇关于在 mongodb 的 api 代码中更新和第二级嵌套数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!