使用变量作为密钥 - Mongo / Node

时间:2016-09-03 07:11:02

标签: node.js mongodb

我需要将MPN作为变量传递,但它被视为文字:

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

...这是findDocument函数:

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

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

试试这样。

sqrt(5)*(1/2 + sqrt(5)/2)**n/5 - sqrt(5)*(-sqrt(5)/2 + 1/2)**n/5

当您像这样创建新对象时

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

同样在es6中你可以这样做

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

希望这有帮助。