klp klp - 2 months ago 20
Node.js Question

How to perform search in Node.js MongoDB

I am trying to perform search on my list in node js and my code below is subjected to that,

exports.searchlistbyfirstname = function (req, res) {
var params = req.params;
var record= db.collection('profile');
record.find( { $text: { $search: params.id} }, (err, result) => {
if (err){ return console.log(err)
}
if(result){
response = {status:'success',data:result};
} else{
response = {status:'fail'};
}
res.send(response);
});

};


I am trying to search
firstname
and I am sure I got wrong.

can anyone please help me

Answer

You can try this query to get your firstname

record.find({
  firstname: {
    $regex: params.id
  }
}, (err, result) => {
  if (err) {
    return console.log(err)
  }
  if (result) {
    response = {
      status: 'success',
      data: result
    };
  } else {
    response = {
      status: 'fail'
    };
  }
  res.send(response);
});