首页 > 解决方案 > 在 throw new Error('record not found') 语句中出现 Nodejs 和 Mongoose 错误

问题描述

我正在使用 mongoose 中间件运行 Reactjs+Nodejs 和 Mongodb 连接。我有一个查找输入商家 ID 是否存在的声明。如果商家 id 存在,则代码可以正常工作,但是当找不到商家 id 时,我正在尝试发送错误文本以响应 js。Nodesjs 中的控件在语句 throw new Error('record not found') 抛出错误时失败。

请在下面找到我的代码。

const jwt = require('jsonwebtoken')
const Merchant = require('../models/merchant')

const auth = async (req, res, next) => {
    try{
        const merchantid = await Merchant.findOne({merchantid: req.body.merchantid  }) // grab user from database
        if (!merchantid) {
            throw new Error('record not found')
        }
        req.merchantid = merchantid
        next()
    } catch (e) {
        res.status(401).send(e)
    }
}

module.exports = auth

请找到我在第 8 行收到的错误消息(抛出新错误('找不到记录'))。

Error: record not found
    at auth (C:\Users\Poorna\Desktop\New_folder\Projects\react\React_new_App\temple_receipt_app\server\middleware\auth.js:8:10)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

提前致谢。

标签: node.jsmongodbmongoose-schema

解决方案


这就是 throw 的工作原理。你想像这样返回调用系统

改变

    throw new Error('record not found')

    res.status(404)

推荐阅读