1

I am creating a API using node js and mongo db. I want to implement a search. Here the following is my code

router.post('/searchstudents', async(req, res) => {


    const qualifications = await Qualification.find({
        qualification: /req.body.searchkey/
    });

    res.send(qualifications);

});

In here this req.body.searchkey is identified as a string and does not give me the output. How to use it as a variable so I can send random values ?

I want to use /someString/ as the like operator in Sql.

Suthura Sudharaka
  • 643
  • 10
  • 25

1 Answers1

1

You can use $regex if you want to search.

router.post('/searchstudents', async(req, res) => {
    const qualifications = await Qualification.find({
        qualification: { $regex: new RegExp(req.body.searchkey) }
    }).lean();
    return res.status(200).json(qualifications);
});

Warning: It's not safe to use regex like that since it can be exploited. Please read this to know more about it. https://stackoverflow.com/a/52727773/8892700

Darvesh
  • 645
  • 7
  • 15