Text search multiple fileds not working in nodejs and mongodb

Viewed 89

I am trying to search by concatenating these firstName,middleName and lastName fields

Here is my model

var lectureSchema = new mongoose.Schema({
 firstName:{
     type:String,
     require:"First Name can\'t be empty "
   },
 middleName:{
     type:String,
     require:"Middle Name can\'t be empty "

 },  
 lastName:{
     type:String,
     require:"Last Name can\'t be empty ",
  },
 email:{
     type:String,
     require:"Email can\'t be empty "
 }
};
lectureSchema.index({firstName:'text', middleName:'text',lastName:'text'});

mongoose.model('Lecture',lectureSchema); 

And also here is my Function respond to search API

module.exports.findLecture=(req,res)=>{
 var query = req.params.query;
 Lecture.find({
      $text: {
          $search:query
      }
      
  }, function(err, result) {
      if (err) throw err;
      if (result) {
          res.json(result)
      } else {
          res.send(JSON.stringify({
              error : 'Error'
          }))
      }
  })

} 

here is the route

router.get('/findLecture/:query',checkerUser.findLecture);

But, this only seems to fetch documents that match the firstName field. It doesn't match middleName and lastName field.someone please help me.

1 Answers

I have implemented query to solve this,

Please follow the link,

https://mongoplayground.net/p/3GW2FYH95tj

You have to use aggregation queries to achieve your requirement.

db.collection.aggregate([
  {
    $project: {
      name: {
        $concat: [
          "$firstName",
          "$middleName",
          "$lastName"
        ]
      }
    }
  },
  {
    $match: {
      name: {
        $regex: "john1unknown1Doe1"
      }
    }
  }
])

Replace "john1unknown1Doe1" with your regex value like new Regex(req.query.search).

Related