Mongoose: find by passing variable

I want to find by passing variable. I have data like this,

{
  "projectId": "12345-service-request",
  "projectVersion": [{
    "version":"1",
    "localConfig": [{
      "port": "3003",
      "mongoURI": "mongodb://localhost:27017/serviceRequest",
      "MQ": "RMQ",
      "logLevel": "2",
      "version": "1.1",
      "created": "03-06-2018 03:11:00 PM",
      "active": "N"
    },
    {
      "port": "3004",
      "mongoURI": "mongodb://localhost:27017/serviceRequest",
      "MQ": "IMQ",
      "logLevel": "1",
      "version": "1.2",
      "created": "07-06-2018 03:11:00 PM",
      "active": "Y"
    }]    
  }]
}

In request, i am getting data like this,

{
    "projectId" : "32804-service-request-service",
    "env" : "local"
    "cloudParam" : {
        "MQ" : "RMQ",
        "logLevel" : "2",
        "active": "N"   
    }
}

So, I am changing keys of cloudParam in request.

let dbQry = renameKeys(cloudParam, function(key, val) {
        return "projectVersion.localConfig."+ key;
    });

    console.log(dbQry);

    // Output : { 'projectVersion.localConfig.MQ' : 'RMQ', 'projectVersion.localConfig.logLevel': '2' , 'projectVersion.localConfig.active': 'N' }

Now, I want to pass dbQry and projectId in Find query. I am passing like below, but it returns nothing,

ProjectConfig.find({'projectId' : projectId,dbQry}).exec(function(err,pc){         
    console.log("## DB Result : "+pc);
});

So, how to pass variable in Find method of Mongoose?

EDIT-- Expected Output:

{
      "port": "3003",
      "mongoURI": "mongodb://localhost:27017/serviceRequest",
      "MQ": "RMQ",
      "logLevel": "2",
      "version": "1.1",
      "created": "03-06-2018 03:11:00 PM",
      "active": "N"
    }

Note: If i get complete document as output, then also it's ok, But how to pass parameters in find query.

1 answer

  • answered 2018-07-12 07:59 Ratan Uday Kumar

    try like below

    ProjectConfig.findOne({ 'projectId': projectId }).exec(function (err, pc) {
    let version = "1.1"; //your version
    let MQ = "RMQ";//your mq
    let versionData = {};
    mydate.projectVersion.forEach(item => {
      let match = item.localConfig.find(ele=> (ele.version == version && ele.MQ == MQ ));
      versionData = (match != null) ? match : {}
    });
        console.log(versionData);
    });
    

    console log result

    {
          "port": "3003",
          "mongoURI": "mongodb://localhost:27017/serviceRequest",
          "MQ": "RMQ",
          "logLevel": "2",
          "version": "1.1",
          "created": "03-06-2018 03:11:00 PM",
          "active": "N"
        }
    

    working example link

    https://jsbin.com/wobedikeze/1/edit?js,console,output