Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 one would normally do this:

db.createCollection('col', function(err, col){
    col.insert({'_id':'wak3ajakar00'});
}

to do this instead:

db.createCollection('col', function(err, col){
    var ID = '_id';
    col.insert({ID:'wak3ajakar00'});
}

When I run the latter code, I end up with a document in collection db.col with a key called ID in addition to a standardly created _id, as opposed to just a key _id with the value wak3ajakar00. This leads me to believe that it isn't actually possible to do this directly.

Instead, I'm now just creating the document that I want to insert ahead of time as follows:

db.createCollection('col', function(err, col){
    var ID = 'wak3ajakar00';
    var key = '_id';
    insertion = {}
    insertion[key] = ID;
    col.insert(insertion);
}

This works exactly like I want it to, but I just wanted to know if there are any better ways to go about this. JavaScript, NodeJS, and MongoDB are all new to me, so I feel like I could easily be missing something. If not, are there any cleaner ways to write the above code in JavaScript?

Best, and thanks,
Sami

like image 622
thisissami Avatar asked Aug 12 '11 23:08

thisissami


2 Answers

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";
like image 79
gilly3 Avatar answered Oct 24 '22 04:10

gilly3


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.

like image 26
Stephan Hoyer Avatar answered Oct 24 '22 06:10

Stephan Hoyer