amine_detter amine_detter - 4 months ago 27
JSON Question

how to create dynamic document keys in mongodb

My problem consists of creating a collection with dynamic fields and undefined names which should be entered by the user. So I tried doing it using variables but it's not working.

This is the code

insertData_dynamic_colone : function(collection) {
var colone1 = "prod";
var colone2 = "prod2";
dbObject.collection(collection).insertOne({
colone1 : "14",
colone2 : "15"
}, function(err, result) {
assert.equal(err, null);
});
},


So on the database I am getting

> db.colone_dynamic.find()
{ "_id" : ObjectId("579af3c4f41e03f0362a5170"), "colone1" : "14", "colone2" : "15" }


But I'm expecting to get

> db.colone_dynamic.find()
{ "_id" : ObjectId("579af3c4f41e03f0362a5170"), "prod" : "14", "prod2" : "15" }

Answer

Use the bracket notation to construct the document dynamically. You need to first create an empty object that will hold the keys and then use the bracket notation to add the dynamic fields to the object:

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

or

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

Or, you can use ES2015 Object initializer syntax (as pointed out by @xmikex83 in comments):

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