relentless-coder
relentless-coder

Reputation: 1536

Mongoose, text search multiple fields not working

Here is my model,

 var InternetSchema = new Schema({
  name: String,
  company: String,
  contactNumber:String,
  accessToken:String,
});

InternetSchema.index({name: 'text', company: 'text');
export default mongoose.model('Internet', InternetSchema);

And here is my function that responds to the search API

export function getSearchAccess(req, res) {
    // const arr = [
    //     {name: req.params.term},
    //     {company: req.params.term}
    // ]
    console.log(req.params.term)
    Internet.find({
       $text: {
           $search: req.params.term
       }
    }).limit(10).exec(function(finderr, finddata) {
        return res.json({ count: 10, data: finddata });
    });

}

But, this only seems to fetch documents that match the name field. It doesn't match the company field.

I have tried testing it in mongo shell, and it doesn't fetch any data for the company but does fetch data for the name

Upvotes: 2

Views: 7244

Answers (3)

Abid
Abid

Reputation: 361

You can find text this using MongooseJS

let query= req.params.term;
Internet.find({name: { $regex: '.*' + query + '.*' } }).limit(10);

Upvotes: 0

aitsamahad
aitsamahad

Reputation: 495

I was having exactly the same problem my two fields that i was wanting to search on were "title" and "description". So the steps should be taken are,

  1. Remove current indexes from the document (except _id).
  2. Now on your model (mine was "event" and schema name was "eventSchema") add index as follows:
eventSchema.index(title: 'text', description : 'text');

Now this code will search in both 'title' and 'description' for the string that is given using params:

const { search } = req.params;
const events = await Event.find({$text: {$search: `${search}`}});

Upvotes: 0

Sergaros
Sergaros

Reputation: 831

try to use '$or' operator:

//examples from my app
//User.js
..
userSchema.index({login: 'text', fullname: 'text', email: 'text'}, {default_language: 'none'});

//query examples:
User.find({"$or": [ { "fullname" : { $search: criteria }}, { "email" : { $search: criteria }}, { "login" : { $search: criteria }}]});
//or regexp
User.find({"$or": [ { "fullname" : { $regex: criteria }}, { "email" : { $regex: criteria }}, { "login" : { $regex: criteria }}]});

Upvotes: 5

Related Questions