CJ101 CJ101 - 5 months ago 7
JSON Question

Holding entire MongoDB insert statement in one variable

I've been trying to create a string, usable by JSON, to insert a set of data into MongoDB. Note that the data is being input, all the information is correct.

However, "finalString" is being treated as an individual variable, and is being input as "finalString" : undefined, and then carries on right into the next value, i.e. undefinedStudent...., rather than undefined, "Student...".

After that, however, the data is input correctly and mongo treats the rest of the variable like a statement. How would I go about getting my script to recognize the variable as one entire statement.

mclient.connect(url[0], function(err, db) {
var dataToJSONFormat = "";
for(var i = 0; i < properties.length; i++) {
dataToJSONFormat += properties[i] + " : '" + values[i] + "'";
if(i < properties.length - 1) dataToJSONFormat += ", ";
}

write("OrderData: {" + JSON.stringify(dataToJSONFormat) + "}");
var finalString = dataToJSONFormat;
db.collection(url[1]).insert(
{
OrderData : {finalString}
}
);
console.log(dataToJSONFormat);
console.log("Data input successful");
db.close();
});

Answer

In JavaScript you don't need to generate the object from string. You can just use the object literal notation something like below.

mclient.connect(url[0], function(err, db) {
    var data = { OrderData:{} }
    for(var i = 0; i < properties.length; i++) {
      //this does the trick. You can assign key values to object on the fly. using obj[key] = value  
      data.OrderData[properties[i]] = values[i]; 
    }
    db.collection(url[1]).insert(data);
    console.log("Data input successful");
    db.close();
});

Check this jsFiddle that shows the concept.