2

I'm trying to get Mongoose to return results in a query when I only give a partial query. For example: I have a 'Company' schema that lists a bunch of companies. A document example:

{
"_id" : ObjectId("57aabeb80057405968de1539"),
"companyName" : "Vandelay Industries",
"owner" : "Ary Vandelay",
"inception" : 2012,
"__v" : 1
}

So if I do a search query like this:

Company.findOne(
    { companyName: Vandelay Industries }, function (err, company) {
        if (company) {
            //do stuff
        }
    });

This will produce the document. But If I do the following, I won't get a result:

Company.findOne(
    { companyName: Vandelay }, function (err, company) {
        if (company) {
            //do stuff
        }
    });

I would like to be able to do these sorts of partial searches and still get a result. Is there any way to do that with Mongoose?

MonkeyOnARock
  • 2,151
  • 7
  • 29
  • 53

4 Answers4

3

In order to achieve this you can use a regex search to get the required result.

var searchKey = new RegExp('Vandelay', 'i')
Company.findOne({ companyName: searchKey }, function (err, company) {
    if (company) {
        //do stuff
    }
});

Refer this stackoverflow post.

Community
  • 1
  • 1
Ananth Pai
  • 1,939
  • 14
  • 15
0

You can use this query to get result on specific value

Company.findOne({"companyName": /Vandelay/},function(err,company){
    if(!err){
        console.log(company);
    }
});
abdulbarik
  • 6,101
  • 5
  • 38
  • 59
0

To get result faster you should use indexing ref https://docs.mongodb.com/manual/text-search/.

db.Company.createIndex( { companyName: "text" } )

then you can search

   db.Company.find( { $text: { $search: "company name" } } )

But this only support full word search not partial, so adding an extra line to this will help

   db.Company.find({ $or: [
            { $text: { $search: query } },
             { companyName: { $regex: '^' + 'copmany name'} }
          ]}

This will help you search the results faster than normal

Pran R.V
  • 1,015
  • 12
  • 21
-1

Are you doing a fulltext search? If you do that:

TagGroup.find({
    $text: {
        $search: text
    }
}, {
    score: {
        $meta: "textScore"
    }
}).sort({
    score: {
        $meta: 'textScore'
    }
})

Try that code below. Also you need create a index on that schema

TagGroupSchema.index({
    "$**": "text"
});

Here is the document

You can use elasticsearch to do that either, when the documents grows, you should consider this way.

crazy_phage
  • 550
  • 9
  • 28