Search code examples
javascriptmongodbmeteorcollectionfs

Set value in a loop to a value which is set in the first loop execution


What I want to do is to set a variable to a value which is set by the first loop execution.

As background information: I'm using CollectionFS to upload multiple files in my meteor app. Now I want to set to all files (beside the first one) the custom field value parent to the id of the first inserted file. I get the id by data._id.

My attempt:

As I'm using a loop for each uploaded file, I thought data is undefined for the first file, so I check if it has a value. In this case also parent would be undefined. For the second file, data is already set, so parent should get data._id as its value.

But this doesn't work properly, as parent is always undefined:

FS.Utility.eachFile(event, function (file) {
    var newFile          = new FS.File(file),
        parent           = (data) ? data._id : undefined;
        newFile.metadata = { parent: parent };

    var data = Images.insert(newFile);
    console.log(data._id); // id of the inserted file

});

Solution

  • data is being redefined on every iteration. Declare it outside of the loop.

    var data;
    FS.Utility.eachFile(event, function(file) { ... });