xtr33me
xtr33me

Reputation: 1106

Dynamic Mongoose Find using AND style query

I have a situation where the user may enter multiple constraints to return back results on. I am trying to perform a "find" in mongoose that I can perform multiple "and"s on. I thought the first block below would return back my results but rather it returns back all results currently in my db. My end goal I was trying to achieve is from the two hex value entries of both "5B6D8B" AND "BA4D2A" provide me the path only if the perc >= 5. If I just pass "{hex: "5B6D8B", 'img.perc': {$gte: 5} }" to find it pulls back a single result which is correct.

clrModel.find([{hex: "5B6D8B", 'img.perc': {$gte: 5} },
{hex: "BA4D2A", 'img.perc': {$gte: 5} }] ,'img.path', function(error,data){});

The second part to this is I would like to, if possible, build the value passed to "find" dynamically. It seems that I can't pass it as a string as it doesn't work. Any ideas on how I can achieve this? The below block is what I was trying to do but it doesnt work. Unsure if it will help in better understanding what I was attempting to do. "finalFind" that is shown below is the result I would pass as the first param to the find query. Thanks in advance!

var hex, perc, finalFind = '{';
for(var i = 0; i < numIndicies; i++){
    finalFind += '{hex:"' + hexArr[i] + '", {perc: {$gte:' + percArr[i] + '}}}';
    //Handle our end character
    if(i !== numIndicies-1)
        finalFind += ',';
    else
        finalFind += '}';
}

------- Edit Below Showing Document Example --------

The below item is representative of a document entry

{
    "__v": 0,
    "_id": {
        "$oid": "51c1ac95f502f20969000022"
    },
    "hex": "BA4D2A",
    "img": [
        {
            "path": "http://example.com/image1.jpg",
            "perc": 10,
            "_id": {
                "$oid": "51c1ac95f502f20969000023"
            }
        },
        {
            "path": "http://example.com/image2.jpg",
            "perc": 20,
            "_id": {
                "$oid": "51c1ac95f502f20969000034"
            }
        }
    ]
}

Upvotes: 0

Views: 1305

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146084

Well, you can't have an AND with 2 values for the same property (hex) as that's not possible, so I assume you want both an AND clause and an OR clause like below. AND is the default for your conditions object, so you just need to $or your hex values.

clrModel.find({
  'img.perc': {$gte: 5},
  $or: [
    {hex: "5B6D8B"},
    {hex: "BA4D2A"}
  ]
}, 'img.path', function(error,data) {....

Another variant that should return the same results:

clrModel.find({
  'img.perc': {$gte: 5},
  hex: {$in: ["5B6D8B", "BA4D2A"]}
}, 'img.path', function(error,data) {....

Upvotes: 1

Related Questions