【发布时间】: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 })
})
})
【问题讨论】: