3zzy 3zzy - 3 months ago 9
Node.js Question

Using variable for a key - Mongo/Node

I need to pass

MPN
as a variable but its taken as a literal:

MongoClient.connect(url, function(err, db) {
if (err) { console.log('err); }
else {
for (var key in products) {
supplier = products[key];
MPN = sanitizeKey(keys[product]['MPN']);
console.log( typeof(MPN), MPN ); // => string manufacturesPn

findDocument(db, product, { MPN : '960-000584' });
// => No document(s) found in [collection] with {"MPN":"960-000584"}!
// Expected: {"manufacturesPn":"960-000584"}
}
}
db.close();
});


... and this is the
findDocument
function:

var findDocument = function(db, collection, queryObj, callback) {
var cursor = db.collection(collection).find( queryObj );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
return doc;
} else {
console.log('No document(s) found in ' + collection + ' with ' + JSON.stringify(queryObj) + '!');
}
});
};


What am I missing here?

Answer

Try like this.

MongoClient.connect(url, function(err, db) { if (err) { console.log('err); } else { for (var key in products) { supplier = products[key]; MPN = sanitizeKey(keys[product]['MPN']); console.log( typeof(MPN), MPN ); // => string manufacturesPn //this is how to asign variable as a key var query = {}; query[MPN] = '960-000584'; findDocument(db, product, query); // => No document(s) found in [collection] with {"MPN":"960-000584"}! // Expected: {"manufacturesPn":"960-000584"} } } db.close(); });

When you create new object like this

var a = "test";
var b = {a: 1234}; <- a is just a key not variable value.

Also in es6 you can do like this

var query = {
   [MPN]: "yourValue"
}; // <- {"manufacturesPn":"yourValue"} 

Hope this helps.