如何在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.

这是代码

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

所以在数据库上我得到

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

但是我希望得到

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

使用括号符号来动态构建文档.您需要首先创建一个将保留键的空对象,然后使用方括号符号将动态字段添加到该对象:

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

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对象初始化程序语法(如@ xmikex83在评论中指出的那样):


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