Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 253
user2787799 Avatar asked Sep 29 '13 13:09

user2787799


People also ask

Is Mongoose better than MongoDB?

Mongoose allows users to conveniently create and manage data in MongoDB. While it is possible to manage data, define schemas, etc. using MongoDB APIs, it is quite difficult to do so. Hence, Mongoose has made lives easier.

What is a query in mongoose?

A Query is what is returned when calling many Model methods. These Query objects provide a chaining api to specify search terms, cursor options, hints, and other behavior.

What is the benefit to using mongoose?

The benefit of using Mongoose is that we have a schema to work against in our application code and an explicit relationship between our MongoDB documents and the Mongoose models within our application.

Do I need mongoose to use MongoDB?

Mongoose is an ODM (Object Data Modeling) library for MongoDB. While you don't need to use an Object Data Modeling (ODM) or Object Relational Mapping (ORM) tool to have a great experience with MongoDB, some developers prefer them. Many Node.


1 Answers

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.

like image 63
JohnnyHK Avatar answered Oct 08 '22 18:10

JohnnyHK