Sejista Carl
Sejista Carl

Reputation: 101

adding dynamic conditions to mongoose find nodejs.. AND, OR in a same query

I am trying to add dynamic conditions using mongoose library

var and_cond = { $and: [] };
var or_cond = { $or: [] };
and_cond.$and.push ({ "doc_no" :  /first/i  })
or_cond.$or.push ({ "doc_type" : /third/i  })

TRModel.find(
            and_cond,
            or_cond
       )

What I expect something which can give me both AND and OR condition work in a query,

The above ended in an abrupt query which is wrong obviously.

title_records.find({ '$and': [ { doc_no: /first/i } ] }, { fields: { '$or': [ { doc_type: /third/i } ] } })

Upvotes: 0

Views: 958

Answers (2)

Akrion
Akrion

Reputation: 18515

You will need to first make sure you are matching the mongoose find parameters which are defined specifically as:

MyModel.find({ <conditions> }, { <projections> }, { <options> }, <callback function>);

e.g.

MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});

So you have to make sure your end result is one object going in into the conditions part of the find.

Next thing is you have to make sure you have one operator from these types:

$and, $or, $not and $not

As your top level one and then you can nest others inside. Like you could have top level $and with multiple $or inside.

Upvotes: 1

B. Fleming
B. Fleming

Reputation: 7220

There are two problems:

  1. You're trying to use two top-level logical operators. To my knowledge, you need to have a single top-level operator from the set of $and, $or, and $nor. You can nest as many as you want within, however.
  2. You're passing in two separate object when what you really want to do is merge the two.

It looks like you're trying to perform your query such that you find all documents that match both the $and condition AND the $or condition. In that case, try the following:

TRModel.find({
    $and: [
        and_cond,
        or_cond
    ]
});

If, however, you want to use one OR the other, you can simply change the top-level $and to $or:

TRModel.find({
    $or: [
        and_cond,
        or_cond
    ]
});

Upvotes: 1

Related Questions