Brug bracket notation: begynd med et tomt objekt, og tilknyt derefter de dynamiske felter til det.
insertData_dynamic_colone: function(collection, colone1, colone2) { var obj = {}; obj[colone1] = "14"; obj[colone2] = "15"; dbObject.collection(collection).insertOne(obj, function(err, result) { assert.equal(err, null); }); } Eller med navnene erklæret inline:
insertData_dynamic_colone: function(collection) { var obj = {}, colone1 = "prod", colone2 = "prod2"; obj[colone1] = "14"; // bracket notation obj[colone2] = "15"; dbObject.collection(collection).insertOne(obj, function(err, result) { assert.equal(err, null); }); } Eller, som @xmikex83 påpegede i kommentarerne, brug ES2015 computed property names:
insertData_dynamic_colone: function(collection) { var colone1 = "prod"; var colone2 = "prod2"; dbObject.collection(collection).insertOne({ [colone1] : "14", // computed property names (ES6) [colone2] : "15" }, function(err, result) { assert.equal(err, null); }); }