Search code examples
javascriptmongodbmongoskin

Mongoskin query check if document $exists using a variable as Query Key


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.


Solution

  • 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.