从多对象req.body更新数组中的多个对象

时间:2017-09-27 18:16:57

标签: javascript node.js mongodb mongoose

好的,我有这个系列:

{
    "_id" : ObjectId("59baa8af86e5df3984674639"),
    "centralPath" : "C:\\Users\\konrad.sobon\\OneDrive - HOK\\GoogleDrive\\Work\\DynamoWork\\142_SeatManifestGenerator\\RVT2018\\CBUEC_HOK_IN-central.rvt",
    "totalFamilies" : 31,
    "unusedFamilies" : 18,
    "oversizedFamilies" : 0,
    "inPlaceFamilies" : 0,
    "createdBy" : "konrad.sobon",
    "createdOn" : ISODate("2017-09-14T20:19:09.525Z"),
    "families" : [ 
        {
            "name" : "Spot Elevation - Target Filled_HOK_I",
            "size" : "1.2Mb",
            "sizeValue" : 1200000,
            "instances" : 0,
            "elementId" : 6158,
            "isFailingChecks" : true,
            "isDeleted" : false,
            "_id" : ObjectId("59bae43d2720015998392905"),
            "tasks" : [],
            "parametersCount" : 0,
            "nestedFamilyCount" : 1,
            "voidCount" : 0,
            "refPlaneCount" : 2,
            "arrayCount" : 0
        }, 
        {
            "name" : "Section Head - Filled_HOK_I",
            "size" : "140kb",
            "sizeValue" : 145760,
            "instances" : 0,
            "elementId" : 8762,
            "isFailingChecks" : true,
            "isDeleted" : false,
            "_id" : ObjectId("59bae43d2720015998392904"),
            "tasks" : [],
            "parametersCount" : 0,
            "nestedFamilyCount" : 1,
            "voidCount" : 0,
            "refPlaneCount" : 3,
            "arrayCount" : 0
        }, 
        {
            "name" : "Railing Tag_HOK_I",
            "size" : "244kb",
            "sizeValue" : 249856,
            "instances" : 0,
            "elementId" : 12426,
            "isFailingChecks" : true,
            "isDeleted" : false,
            "_id" : ObjectId("59bae43d2720015998392903"),
            "tasks" : [],
            "parametersCount" : 3,
            "nestedFamilyCount" : 1,
            "voidCount" : 0,
            "refPlaneCount" : 2,
            "arrayCount" : 0
        }, 
        {
            "name" : "Fixed",
            "size" : "316kb",
            "sizeValue" : 323584,
            "instances" : 0,
            "elementId" : 3499132,
            "isFailingChecks" : true,
            "isDeleted" : false,
            "_id" : ObjectId("59bae43d27200159983928e7"),
            "tasks" : [],
            "parametersCount" : 4,
            "nestedFamilyCount" : 2,
            "voidCount" : 0,
            "refPlaneCount" : 18,
            "arrayCount" : 0
        }
    ],
    "__v" : 0
}

我要做的是发送更新该集合中某些“家庭”的请求。我有这些Family对象的数组,如下所示:

{"key": [
            {
                "name" : "New Spot Elevation - Target Filled_HOK_I",
                "size" : "1.2Mb",
                "sizeValue" : 1200000,
                "instances" : 0,
                "elementId" : 6158,
                "isFailingChecks" : true,
                "isDeleted" : false,
                "Id" : "59bae43d2720015998392905",
                "tasks" : [],
                "parametersCount" : 0,
                "nestedFamilyCount" : 1,
                "voidCount" : 0,
                "refPlaneCount" : 2,
                "arrayCount" : 0
            }, 
            {
                "name" : "New Section Head - Filled_HOK_I",
                "size" : "140kb",
                "sizeValue" : 145760,
                "instances" : 0,
                "elementId" : 8762,
                "isFailingChecks" : true,
                "isDeleted" : false,
                "Id" : "59bae43d2720015998392904",
                "tasks" : [],
                "parametersCount" : 0,
                "nestedFamilyCount" : 1,
                "voidCount" : 0,
                "refPlaneCount" : 3,
                "arrayCount" : 0
            }
        ]}

现在,我需要能够找到并更新每个指定的系列。我以为我可以迭代传入的数组(我在req.body中发送它),然后创建一个需要更新的ID数组,这样我就可以在mongo中使用$ in运算符了。之后,我认为我可以使用id来检索我感兴趣的属性,并使用$ set来更新它们。我的尝试在这里:

module.exports.updateMultipleFamilies = function (req, res) {
    var id = req.params.id;
    var famIds = []; // [ObjectId]
    var newFamilies = {}; // {"id_string" : family}
    for(var key in req.body) {
        if(req.body.hasOwnProperty(key)){
            for(var i = 0; i < req.body[key].length; i++){
                var family = req.body[key][i];
                newFamilies[family.Id] = family;
                famIds.push(mongoose.Types.ObjectId(family.Id));
            }
        }
    }

    Families
        .updateMany(
            {_id: id, 'families._id': {$in: famIds}},
            {$set: {'name': newFamilies["current_document_id_help"].name}}, function(err, result){
                if(err) {
                    res
                        .status(400)
                        .json(err);
                } else {
                    res
                        .status(202)
                        .json(result);
                }
            }
        )
};

编辑:

所以我尝试了bulkWrite调用的不同方法。它不会给我错误,但它也不会更新任何内容。有什么想法吗?

module.exports.updateMultipleFamilies1 = function (req, res) {
    var id = req.params.id;
    var bulkOps = [];

    for(var key in req.body) {
        if(req.body.hasOwnProperty(key)){
            bulkOps = req.body[key].map(function(item){
                return {
                    'updateOne': {
                        'filter': {'_id': id, 'families._id': mongoose.Types.ObjectId(item.Id)},
                        'update': {'$set': {'families.$.name': item.name}},
                        'upsert': false
                    }
                }
            })
        }
    }

    Families.collection
        .bulkWrite(
            bulkOps,
            {'ordered': true, w:1}, function(err, result){
            if(err) {
                res
                    .status(400)
                    .json(err);
            } else {
                res
                    .status(202)
                    .json(result);
            }
        })

};

1 个答案:

答案 0 :(得分:-1)

您需要获取系列数组,更改应用程序中的代码,然后再次更新系列数组。 或者您可以尝试{$ set:{&#39;系列。$。name&#39;:newFamilies [&#34; current_document_id_help&#34;]。name} } 但我不确定这不会更新你所有的家庭

第一个解决方案:

&#13;
&#13;
var id = req.params.id;
    yourCollation.findById(id,function(err, doc){
      
      if(req.body.key && req.body.key.constructor === Array){
          for(var i = 0; i < req.body.key.length; i++){
            for(var x in doc.families ){
               if(family.id === doc.families[x].id){
                  doc.families[x] = family;
               }
            }
          }
      }
    
    
    doc.save()
    })
&#13;
&#13;
&#13;