Search code examples
node.jsmongodbmongoose-schema

Nodejs and Mongoose error at throw new Error('record not found') statement


I am running Reactjs+Nodejs and Mongodb connection using mongoose middleware. I have an statement for finding the input merchant id exist or not. If merchant id exists the code works fine but when merchant id not found i am trying to send the error text to react js. the control failed in Nodesjs while throwing the error at statement throw new Error('record not found').

Please find my code below.

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

Please find error message i am getting at line number 8(throw new Error('record not found')).

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)

Thanks in Advance.


Solution

  • this is how throw works. you want to return to the calling system something like this

    change

        throw new Error('record not found')
    

    to

        res.status(404)