【发布时间】:2021-06-15 07:03:18
【问题描述】:
我很难同时更改对象的多个属性。我的模型如下:
const Schema = new Schema({
main_object:{
object1:{
0: {
logic: false,
text: "Hi"},
1: {
logic: false,
text: "wow"},
2: {
logic: false,
text: "Hello"},
3: {
logic: false,
text: "sad"},
},
object2:{
0: false,
1: false,
2: false
},
}});
在我的控制器内部,我有更新功能:
async my_update(req, res) {
const filter = { my_filter: req.body.my_filter };
const input = [0 2]; //This entry may vary.
const mydata = await MyModel.updateOne(filter,
{
// I know the code below is not suitable.
for (i = 0; i < input.length; i++) {
$set: {"main_object.object1.input[i].logic":true};
}
// I want the line above to do dynamically:
// $set: {"main_object.object1.0.logic":true}
// $set: {"main_object.object1.2.logic":true}
});
return res.json(mydata)
},
【问题讨论】:
-
如果您将模型更改为布尔数组,而不是具有名为 0、1、2、3 等字段的复杂对象,您会更开心。
标签: reactjs mongodb object mongoose backend