1

Ok, I have this collection:

{
    "_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
}

What I am trying to do is send a request to update certain "families" in that collection. I have an array of these Family objects looking like this:

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

Now, I need to be able to find and update each of the specified families. I thought that i can just iterate over the incoming array (I am sending it in a req.body), and then make an array of Ids that would need to be updated so i can use the $in operator in mongo. After that, i thought that I can use the id, to retrieve the properties that I am interested and just use $set to get them updated. My attempt here:

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);
                }
            }
        )
};

Edit:

So i tried a different approach with the bulkWrite call. It doesn't give me errors but it also doesn't update anything. Any ideas why?

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);
            }
        })

};
konrad
  • 3,544
  • 4
  • 36
  • 75
  • Check out this answer here: https://stackoverflow.com/questions/40904007/mongodb-update-multiple-subdocuments-with-or-query - You will need to update every sub document individually in your upper loop, I'm afraid, where you're currently constructing your `newFamilies` array. – dnickless Sep 27 '17 at 18:49

1 Answers1

-1

you need to take the families array , change the code in the app and then update the families array again. or you can try do {$set:{'families.$.name':newFamilies["current_document_id_help"].name} } but im not sure if that wont update all you families

first solution:

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()
    })
Amit Wagner
  • 3,134
  • 3
  • 19
  • 35