MonkeyOnARock MonkeyOnARock - 2 months ago 11
Node.js Question

Doing partial search with mongoose

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?

Answer

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.

Comments