How to create dynamic document keys in mongodb

My problem is to create a collection with dynamic fields and undefined names that must be entered by the user. So I tried to do this with variables, but it does not work.

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 in the database I get

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

But I expect to get

> db.colone_dynamic.find()
    { "_id" : ObjectId("579af3c4f41e03f0362a5170"), "prod" : "14", "prod2" : "15" }
+1
source share
3 answers

Use a notation bracket to dynamically build a document. First you must create an empty object that will hold the keys, and then use parenthesis notation to add 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);         
    });
}

ES2015 Object initializer ( @xmikex83):

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

Try:

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

You want to insert a document that is being generated dynamically. Not very dynamic indexing. 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);         
    });
}, 
+1
source

Source: https://habr.com/ru/post/1690351/


All Articles