0

Using Mongoskin, I want to check if a document exists in a MongoDB collection where every document has a one unique key and an array as its value. This code works perfectly:

db.collection('buyerRec').find({ "abcd" : { $exists : true }}, { _id:0 }).toArray(function(err, doc) {
  ...
});

The "abcd" document is found. However, in the actual system's design the query key of the document is not known in advance and so I need to use a variable in place of "abcd". I can't find the combination that works. It always returns an empty array, in both failing cases-

Failing example-1:

console.log("idCode: " + typeof idCode + " " + idCode); // idCode: string abcd

db.collection('buyerRec').find({ idCode : { $exists : true }}, { _id:0 }).toArray(function(err, doc) {
  ...
});

Failing example-2:

console.log("idCode: " + typeof idCode + " " + idCode); // idCode: string abcd

var query = "\"" + idCode + "\"";
console.log("query: " + typeof query + " " + query);  // query: string "abcd"

db.collection('buyerRec').find({ query : { $exists : true }}, { _id:0 }).toArray(function(err, doc) {
  ...
});

To me, one of those 2 failing examples should have duplicated the intended operation of the first example. Can somebody please steer me as to how I need to re-code this ? Thx.

Ric
  • 796
  • 12
  • 28

1 Answers1

1

I think your problem may be creating js object using variables for property name. you may try like the following:

 fieldName = "abcd"
 var query = {};
 query[fieldName] = {"$exists": true};
 db.collection('buyerRec').find(query)

But the above code is actually not that good, cause fieldName is not passed as parameter. In my .mongorc.js(mongo shell will load .mongorc.js every time it starts), I write function for this case, FYI.

 DBCollection.prototype.has = function(fieldName) {
   var query = {}; // construct a empty object
   query[fieldName] = {"$exists": true};
   return db.getCollection(this._shortName).find(query).pretty();
 }

Then you can just write query like:

 db.buyerRec.has("abc") // in mongo shell

But, I think you actually have to write your own function cause mine is just focusing on checking whether some key exists or not. Anyway, hope it helps.

Community
  • 1
  • 1
Allen Chou
  • 1,229
  • 1
  • 9
  • 12
  • That was a real bear and time soaker for me but your first code set nailed it. I can definitely understand why your code works. On my 2 failing examples the inner variable is a string so I assumed it would be evaluated. Maybe if the MongoDB/Mongoskin docs were more expansive it would say that an inner var will not be evaluated but must be included as part of the complete query object. That's how I understand it now. Thx. – Ric Jul 26 '15 at 04:21