Search code examples
node.jsjsonundefinedstringifyminio

Appending chunked data to a variable gives an unexpected result


I'm trying to add a JSON object which comes from minio file to MongoDB

But the data is like undefined[{"field":"value"}]

Here is my code:

var miniData
minioClient.getObject(fileData.type,fileData.userId+fileData.fileName,function(err,exData) {
    exData.on('data', async function (chunck) {               
        miniData += chunck;
    });
    exData.on('end',async function () {
        console.log(miniData)
        excelDb.create({ excelArray:miniData}) 
    });
});

and in MongoDB document it is stored as:

{
    "_id" : ObjectId("5e0b02b9775cee50051b2547"),
    "excelArray" : "undefined[{\"FIELD\":\"VALUE\"}
}

I want a JSON array in my document.


Solution

  • Give the miniData an initial value. If you won't do that, it is implicitly undefined and undefined plus string makes the undefined to bo converted to a word. See the examples below.

    Without initializing the variable:

    var miniData;
    
    miniData += 'a string';
    
    console.log(miniData);

    With an initial value:

    var miniData = '';
    
    miniData += 'a string';
    
    console.log(miniData);

    So in your code it should be like this:

    var miniData = ''; // initialize the variable with an empty string
    minioClient.getObject(fileData.type,fileData.userId+fileData.fileName,function(err,exData) {
        exData.on('data', async function (chunck) {               
                miniData += chunck;
        });
        exData.on('end',async function () {
            console.log(miniData)
            excelDb.create({ excelArray:miniData}) 
        });
    });
    

    And if you want to have an actual array in the MongoDB document, you need to JSON.parse the miniData before inserting so the final solution should be like this:

    var miniData = ''; // initialize the variable with an empty string
    minioClient.getObject(fileData.type,fileData.userId+fileData.fileName,function(err,exData) {
        exData.on('data', async function (chunck) {               
                miniData += chunck;
        });
        exData.on('end',async function () {
            console.log(miniData)
            excelDb.create({ excelArray: JSON.parse(miniData)}) 
        });
    });