繁体   English   中英

更新文档中的嵌入式数组(如果存在),否则创建一个新文档MongoDB NodeJS

[英]Update an embedded array inside an document if it exists otherwise create a new document MongoDB NodeJS

如果该字段存在,我想更新嵌入式数组,否则用指定的字段制作一个新文档。

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"
               }
            ]
         }
      ]
   }
]

因此,我最终解决了我的问题,并且将解决方案发布给可能具有与我所经历的相似或接近的人。

我使用的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));
            });
      }
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM