[英]How to update an Array of Objects field in MongoDb
I have a data structure, like so我有一个数据结构,就像这样
{
_id: '',
name: 'A',
financialReports: {
monthlyBill: 20,
monthlyBillReports: [
{
month: 'JAN',
isPaid: true
},
{
month: 'FEB',
isPaid: false
},
{
month: 'MAR',
isPaid: false
},
{
month: 'APR',
isPaid: false
},
...
]
}
},
...
How should I dynamically update financialReports.monthlyBillReports[i].isPaid
to true?我应该如何将financialReports.monthlyBillReports[i].isPaid
动态更新为 true? I got array of data that indicate to month field in Database from front-end ['FEB', 'APR']
, But I am not sure if I could iterate over the array and make update query to Database.我从前端['FEB', 'APR']
获得了指示数据库中月份字段的数据数组,但我不确定是否可以遍历数组并对数据库进行更新查询。
you can do a loop something like:你可以做一个循环,比如:
let yourArray = ['FEB', 'APR'] // just mocking the array
yourArray.forEach((mo)=>{
collectionName.findOneAndUpdate(
{_id: 'document id goes here'},
{ '$set': {'financialReports.monthlyBillReports.$[frFilter].isPaid': true}},
{ arrayFilters: [ {frFilter.month: mo} ], multi: true}
).then(
//do whatever you need here
)
})
or in a more straight forward manner:或更直接的方式:
collectionName.findOneAndUpdate(
{_id: 'document id goes here'},
{ '$set': {'financialReports.monthlyBillReports.$[frFilter].isPaid': true}},
{arrayFilters: [ {frFilter.month: {$in: yourArray} } ], multi: true}
).then(
//do whatever you need here
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.