felix-cao / Blog

A little progress a day makes you a big success!
31 stars 4 forks source link

mongoose 多条件模糊查询 #72

Open felix-cao opened 5 years ago

felix-cao commented 5 years ago

mongoose 如何实现类似于SQL中 name like '%keyword%' or email like '%keyword%' 这种多条件模糊查询的问题。主要用到 $or 和正则表达式

public async search(req: Request, res: Response) {
    const keyword = req.query.keyword; // 从URL中获取参数
    const reg = new RegExp(keyword, 'i') // 不区分大小写
    const coinArr = await coinsBase.find(
    {
      $or: [
        {name: {$regex: reg}},
        {symbol: {$regex: reg}}
      ]
    })
    res.json(coinArr);
}

Reference