i want to get the value of this variable outside the function const custDetail = await registeredUser.findOne(req.params);
const dashboardReq = async (req, res, next) => { try { const regCust = await registeredUser.findOne({ mobile: req.params.mobile }); if (regCust == null) { console.log("No user found"); } else { const custDetail = await registeredUser.findOne(req.params); } res.status(201).json({ status: "success", data: { regCust }, }); } catch (error) { res.status(400).json({ status: "fail", data: next(error), }); } };
Advertisement
Answer
Edit a simple way to pass data to another function using res.locals
router:
router.get('getDashboardRef/:mobile', userCtl.dashboardReq, userCtl.nextFunction)
dashboardReq
const dashboardReq = async (req, res, next) => { try { res.locals.regCust = await registeredUser.findOne({ mobile: req.params.mobile }); if (!res.locals.regCust) { console.log("No user found"); throw new Error("No user found") } else { res.locals.custDetail = await registeredUser.findOne(req.params); next() } } catch (error) { res.status(400).json({ status: "fail", data: error, }); } };
nextFunction
const nextFunction = (req, res) => { //do stuff with res.locals.custDetail res.status(201).json({ status: "success", data: { res.locals.regCust }, }); }