Ravi Hooda
Ravi Hooda

Reputation: 57

Searching in mongodb using just few keywords

I'm using node js,mongoose,express and mongodb.

I have created simple form, in which you enter you full name and it searches in database and return your other details .

Is it possible to search using only few words out of the whole name? e.g. if the user wants to search for "abc xyz",can user do the same using only "abc" or "xyz"

this is my original route:

app.get("/",function(req,res){

  var name = req.query.name;
  details.findOne({fullname:name},function(err,foundAsked){
      if(err){console.log("ERROR!!!");}
      else{res.render("Details.ejs",{foundAsked:foundAsked,name:name}); }
  });
 }); 

Is it possible to do that?if yes,then how can I implement that ?

Upvotes: 1

Views: 423

Answers (2)

wjvander
wjvander

Reputation: 601

You could use regex to partially match on certain fields like so

const query = {
    fullname: {
        $regex: req.query.name,
        $options: 'i'
    }
};

details.find(query, function(err, foundAsked){
  ...
})

Where the i in query is to make it case insensitive.

In the case of using partial search, I would recommend not using findOne as that might be misleading to the user to only return a single result if he/she types let's say A

Upvotes: 1

Jeremy Thille
Jeremy Thille

Reputation: 26370

Yes, you can use regexes for that :

details.findOne({ fullname : /.*(?:abc|xyz).*/gi }, .....

Upvotes: 1

Related Questions