Reputation: 321
Currently, I have the following route for a text search.
router.post("/visit", middleware.isLoggedin, function(req,res){
subject.find({Subject_Name: req.body.user} ).sort('Visit_date').exec(function(err,returnedsubjects){
if(err){
console.log(err);
} else {
console.log(returnedsubjects);
res.render("visit",{returnedsubjects: returnedsubjects);
}
});
});
It works fine. But as you can see the subject_name has to match exactly. I need "david" or "David" to find collections where the Subject_Name = "David Warner" for example.
Tried this suggestion. How to query MongoDB with "like"?. Did not work.
Tried this
subject.find({Subject_Name: /req.body.user/} )
and this
subject.find({"Subject_Name": /req.body.user/} )
no luck :(.
Any help is appreciated. Thanks!
Upvotes: 1
Views: 518
Reputation: 566
Create a text index on the Subject_Name field of our document using the following query :
subject.index({Subject_Name:"text"})
then you can search using $text and $search like this :
var text = req.body.user;
subject.find({ $text:{$search: text} });
So let's say that you have created the following Schema :
var subjectschema = new mongoose.Schema({ Subject_Name: { type: String, index: true },etc)}
you have to create the index in the schema's file so your schema file will look like this :
var subjectschema = new mongoose.Schema({
Subject_Name: { type: String, index: true },
etc
)};
subjectschema.index({Subject_Name:"text"};
then start searching in the route :
subjectschema.find( {$text:{$search: req.body.user} }).then(result=>{
if (result)
{
//do something with your code
console.log(result);
}
})
So now if we are searching for "david" the above query returns the following documents containing the keyword "david" in their Subject_Name field.
Upvotes: 2