【问题标题】:How to change various attributes of an object in MongodB?如何更改 MongodB 中对象的各种属性?
【发布时间】: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


【解决方案1】:
const Schema = new Schema({
    main_object:{
      object1:[],
      object2:[]
}});

【讨论】:

  • 感谢您的回复。但是,我想在不使用数组的情况下解决这个问题,因为这个答案将我限制在更复杂的问题上。
【解决方案2】:

如果您希望动态选择元素,请动态构建字段名称字符串。

$set: {"main_object.object1."+i+".logic":true}

然后通过映射输入数组来构建命令的更新部分:

input.map( function(i) { return {"$set": {"main_object.object1."+i+".logic":true}})

【讨论】:

  • 在代码内部,无法应用您的建议。特别是在这部分“main_object.object1.”+i+“.logic”:true。但是,我对您的建议有所了解。谢谢。
【解决方案3】:

在我的控制器内部:

async my_update(req, res) {
        const filter = { my_filter: req.body.my_filter };
        const input = [0, 2]; //Variable input
        const field = input.map((item, i) => [`main_object.object1.${item}.logic`, true]); // Create the fields dynamically. Output: list of key-value pairs.
        const update_operator = {$set: Object.fromEntries(field) } // Transforms a list of key-value pairs into an object.
        const mydata = await MyModel.updateOne(filter,
            update_operator,
            { upsert: true });
        return res.json(mydata)
    },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多