简体   繁体   中英

How to make a variable in mongoose regular expression?

I need a way to implement a variable pattern in mongoose:

router.get('/search/:name', async(req, res) => {
    name = req.params.name;
    const products = await Product.find({ name: /.*name*/i }).limit(10);
    res.send(products);
});

I want to be able to change the name variable.

You can use Template literal and RegExp constructor

 let name = 'xyz' let reg = `.*${name}.*` let regex = new RegExp(reg,'i') console.log(regex) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM