1. 单条件模糊查询

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

	const name =  new RegExp(req.body.name, 'i');

	Client.find({ name }).then((data) => {
    res.send({
      code: 200,
      msg: '查询成功',
      data
    })
  }).catch((e) => {
    console.log(e)
    res.send({
      code: 500,
      msg: '查询失败'
    })
  })
})

2. 多条件模糊查询

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

  // 循环处理函数值为查询 key arr: ['name', 'phone'];返回查询对象
  const regFn = (arr) => {
    const params = {}
    arr.forEach(key => {
      // 如果请求体为空值的时候则不加入判断 (这块具体逻辑看你需求写)
      if (!req.body[key]) return
      // 注意传入的值的type是否符合你自己定义的,如果需求不一可自己改
      params[key] = new RegExp(req.body[key], 'i')
    });
    return params
  }
 
  Client.find(regFn(['name', 'phone'])).then((data) => {
    res.send({
      code: 200,
      msg: '查询成功',
      data
    })
  }).catch((e) => {
    console.log(e)
    res.send({
      code: 500,
      msg: '查询失败'
    })
  })
})

3. 分页查询


 // 失败后的模板
 const errorTem = (msg, error) => res.send({
   code: 500,
   msg,
   error
 });
 // 查詢成功后数据返回的模板
 const successTem = (msg, data) => ({
   code: 200,
   msg,
   data
 })
// 接口逻辑
router.post('/list', (req, res) => {
  let {
    pageSize, // 每页多少条
    pageNo, // 当前页
  } = req.body

  const regFn = (arr) => {
    const params = {}
    arr.forEach(key => {
      if (!req.body[key]) return
      params[key] = new RegExp(req.body[key], 'i')
    });
    return params
  }
  // 记录查询后的状态(防止查询多次)
  const find = Client.find(regFn(['name', 'phone']));
  // 此处为了获取总数
  find.then((datas) => {
    // 此处是分页查询  limit:获取多少条数据;skip:跳过多少条数据
    find.limit(pageSize).skip(pageSize * (pageNo - 1)).then((data) => {
      res.send(successTem('查询成功', {
        data,
        total: datas.length
      }))
    }).catch(e => res.send(errorTem('查询失败', e)))
  }).catch(e => res.send(errorTem('查询失败', e)))
})
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐