Is there any way to use a dynamic key with node-mongodb-native?

后端 未结 2 1704
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 00:09

Is there any way to use dynamic keys with the node-mongodb-native driver? By this I mean having a variable hold the key instead of using the key directly.

As in when

相关标签:
2条回答
  • 2021-01-06 00:46

    2020 Edit: Object literals can now be created in a couple of handy new ways:

    You can now use a variable as a property name in an object literal by wrapping it in square brackets:

    const ID = "_id";
    col.insert({ [ID]: "wak3ajakar00" });
    

    You can use the variable name as the property name, and the variable value as the property value in an object literal like this:

    const _id = "wak3ajakar00";
    col.insert({ _id });
    

    Original Answer from 2011:

    In object literal syntax, you cannot use a variable as the key name, only values. The way to do it, is the way you already discovered - create your object first, then add the property as a separate step using square bracket notation.

    var obj = {};
    var ID = "_id";
    obj[ID] = "wak3ajakar00";
    
    0 讨论(0)
  • 2021-01-06 01:02

    You can write a small function that creates such an object

    var obj = function(key, value, obj) {
      obj = obj || {};
      obj[key] = value;
      return obj;
    }
    
    // Usage
    foo = obj('foo' + 'bar', 'baz');
    // -> {'foobar': 'baz'}
    
    foo = obj('stack' + 'over', 'flow', foo);
    // -> {'foobar': 'baz', 'stackover': 'flow'}
    

    Don't know if calling this function obj is a good idea.

    0 讨论(0)
提交回复
热议问题