【问题标题】:How to return a custom message instead of an empty array from a Mongoose Find query when no results are found未找到结果时如何从 Mongoose Find 查询返回自定义消息而不是空数组
【发布时间】:2021-06-27 06:05:55
【问题描述】:

我正在尝试在执行mongoose.find 查询时返回一条自定义消息,但它在系统上找不到任何内容。

目前我有以下内容并且它有效,但我想知道是否有更好的方法来完成我正在做的事情。

// <status> => one of ["valid", "expired", "attributed"]

const getByStatus = (status) => {
  return new Promise((resolve, reject) => {
    PhotoCodes.find({ status: status })
      .then((response) => {
        resolve(response)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
router.post('/byStatus', (req, res, next) => {
  const { status } = req.body

  photoCodesModel
    .getByStatus(status)
    .then((response) => {    
      if (response.length == 0 ) {
        res.status(404).send('Not Found') // [ASK]: If response is an empty "[]" treat it as nothing was found. Is there a better way of doing this?
      } else {
        res.status(200).json({ result: 'ok', data: response })
      }
    })
    .catch((error) => {
      res.status(400).json({ result: 'ok', error: error })
    })
})

【问题讨论】:

    标签: node.js api mongoose


    【解决方案1】:

    你可以使用 async/await 来做,像这样

    const getByStatus = async (status) => {
        const photo =   await PhotoCodes.find({ status: status })
        return photo   .
      }
    
    router.post('/byStatus',async (req, res, next) => {
      const status = req.body.status;
      try {
      const photo = await getByStatus(status)
      if(photo.length!==0) {
        return res.status(200).json({ result: 'ok', data: photo })
      }
        return res.status(404).json({message : "treat it as nothing was found"})
      }
      catch(error) {
        return res.status(400).json({ result: 'ok', error: error })
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多