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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With