【问题标题】:Update an embedded array inside an document if it exists otherwise create a new document MongoDB NodeJS如果存在,则更新文档中的嵌入数组,否则创建一个新文档 MongoDB NodeJS
【发布时间】:2016-08-04 07:58:55
【问题描述】:

如果该字段存在,我想更新一个嵌入数组,否则创建一个包含指定字段的新文档。

tldr:我有以下更新查询,它只更新第一个文档中的嵌入数组。例如:如果 mac_address 不存在于第一个文档的嵌入数组 'devices' 中,则它不会在其他文档中查找。

要设置/更新设备的状态,我有更新查询并插入新数据(如果不存在);我正在更新函数中通过 if(!result.nModified) 检查条件。

当我运行此代码时,它只会在第一个文档中查找 mac_address(如果存在),它会更新...是的,它可以工作!

如果它不存在 -> 它会创建一个新文档。是的,它有效。

然后如果要检查新文档中最后插入的mac_address,它会重新插入它并形成重复。

更新功能仅适用于第一个文档,它会跳过其余部分。

任何帮助将不胜感激。上周左右我一直在寻找解决方案。尝试了所有可能的解决方案;但它的行为方式与我指定的方式不同。

mac 和 state 是在这段代码之前定义的变量:

  db.devices.update({
      'devices.mac_address': mac
    }, {
      $set: {
        'devices.$.state': state
      }
    },
    function(err, result) {
      if (err) {
        console.log('error: ' + err);
      }
      console.log('result-->' + JSON.stringify(result));

      if (!result.nModified) {
        db.devices.insert({
            name: 'undefined',
            'devices': [{
              '_id': new mongojs.ObjectID(),
              'name': 'undefined',
              'type': 'undefined',
              'state': state,
              'ip_address': ip_address,
              'mac_address': mac,
              'update_timestamp': new Date(),
              'power': [{
                'value': '22',
                'time': new Date()
              }]
            }]
          },
          function(err, result) {
            if (err) {
              console.log('error: ' + err);
            }
            console.log('result-->' + result);
          });
      }
    });

这是我的 JSON 文档。

[
   {
      "_id": "579a8116077f4a6fc78188c8",
      "name": "Bedroom",
      "devices": [
         {
            "_id": "579a82ebe3648480708be146",
            "name": "Smart Switch",
            "type": "switch",
            "state": "on",
            "ip_address": "192.168.4.22",
            "mac_address": "5c:cf:7f:03:35:ab",
            "update_timestamp": "2016-07-28T22:10:51.957Z",
            "power": [
               {
                  "value": "5000",
                  "time": "2016-07-28T22:10:51.957Z"
               }
            ]
         },
   {
      "_id": "57a2e0b1a6fdb70d35e95dfb",
      "name": "Living Room",
      "devices": [
         {
            "_id": "57a2e0b1a6fdb70d35e95dfa",
            "name": "Ceiling Fan",
            "type": "switch",
            "state": "disconnected",
            "ip_address": "142.58.184.155",
            "mac_address": "5c:cf:7f:03:35:aa",
            "update_timestamp": "2016-08-04T06:29:05.247Z",
            "power": [
               {
                  "value": "120",
                  "time": "2016-08-04T06:29:05.247Z"
               }
            ]
         }
      ]
   }
]

【问题讨论】:

    标签: arrays node.js mongodb


    【解决方案1】:

    所以我最终解决了我的问题,我将我的解决方案发布给任何可能与我遇到类似或接近的人。

    我使用的 if 条件都错了。我正在检查'nModified'与!。我不得不用 nModified === 0 替换它,因为当没有什么要更新的时候它返回 0 并且它告诉我们这是一条新记录。

    这是修改和更新的工作代码:

    db.test.update({
          'devices.mac_address': mac
        }, {
          $set: {
            'devices.$.state': state,
            'devices.$.update_timestamp': new Date(),
          },
        $push: {'devices.$.power': {'value': power, 'time': new Date()}}
        }, {
          upsert: false
        },
        function(err, result) {
          if (err) {
            console.log('error: ' + err);
          }
    
          console.log('Updated Existing Device: ' + JSON.stringify(result));
          if (result.nModified === 0) {
            console.log('NEW DEVICE!!');
    
              db.test.insert({
                  'room_name': 'Unassigned',
                  'devices': [{
                    'name': 'Unassigned',
                    'type': 'Unassigned',
                    'state': state,
                    'ip_address': ip_address,
                    'mac_address': mac,
                    'update_timestamp': new Date(),
                    'power': []
                  }]
    
                },
                function(err, result) {
                  if (err) {
                    console.log('error: ' + err);
                  }
                  console.log('NEW DEVICE ADDED RESULTS: ' + JSON.stringify(result));
                });
          }
        });
    

    【讨论】:

      猜你喜欢
      • 2019-08-04
      • 2021-02-24
      • 1970-01-01
      • 2018-09-13
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      相关资源
      最近更新 更多