user2787799
user2787799

Reputation: 237

Mongoose or query

I need to find documents based on multiple text fields.

var term = new RegExp(req.query.search, 'i');
.find({ company_name: { $regex: term }});

Using the above works great. However, when I try to add an additional field using

.find(...).or([{ bio: { $regex: term }}]);

it fails to retrieve any records. I need to do this for a few more fields.

The schema has the different text fields indexed, but not together as a single multi-field index. Would this work better and if so, are there any clear examples of this? The documentation that I found was quite sparse.

Any ideas?

Upvotes: 7

Views: 9213

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312115

Put both fields into an array that's passed to or:

.find().or([{ company_name: { $regex: term }}, { bio: { $regex: term }}]);

Separate single-field indexes are what you want as each or term is executed as a separate query.

Upvotes: 10

Related Questions