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.
Solution 1:
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);
});
}
Solution 2:
Try:
insertData_dynamic_colone: function(collection) {
var data = {
colone1: "prod",
colone2: "prod2"
};
dbObject.collection(collection).insertOne(data, function(err, result) {
assert.equal(err, null);
});
},
Solution 3:
You want to insert document which are formed dynamically.Not really dynamic indexing right. You can use the following to achieve what you want.
insertData_dynamic_colone : function(collection) {
var colone1 = "prod";
var colone2 = "prod2";
var insertObj = {};
insertObj[colone1] = "14";
insertObj[colone2] = "15";
dbObject.collection(collection).insertOne(insertObj, function(err, result) {
assert.equal(err, null);
});
},
Post a Comment for "How To Create Dynamic Document Keys In Mongodb"