i want to get the value of this variable outside the function const custDetail = await registeredUser.findOne(req.params);
JavaScript
x
21
21
1
const dashboardReq = async (req, res, next) => {
2
try {
3
const regCust = await registeredUser.findOne({ mobile: req.params.mobile });
4
5
if (regCust == null) {
6
console.log("No user found");
7
} else {
8
const custDetail = await registeredUser.findOne(req.params);
9
}
10
res.status(201).json({
11
status: "success",
12
data: { regCust },
13
});
14
} catch (error) {
15
res.status(400).json({
16
status: "fail",
17
data: next(error),
18
});
19
}
20
};
21
Advertisement
Answer
Edit a simple way to pass data to another function using res.locals
router:
JavaScript
1
2
1
router.get('getDashboardRef/:mobile', userCtl.dashboardReq, userCtl.nextFunction)
2
dashboardReq
JavaScript
1
19
19
1
const dashboardReq = async (req, res, next) => {
2
try {
3
res.locals.regCust = await registeredUser.findOne({ mobile: req.params.mobile });
4
5
if (!res.locals.regCust) {
6
console.log("No user found");
7
throw new Error("No user found")
8
} else {
9
res.locals.custDetail = await registeredUser.findOne(req.params);
10
next()
11
}
12
} catch (error) {
13
res.status(400).json({
14
status: "fail",
15
data: error,
16
});
17
}
18
};
19
nextFunction
JavaScript
1
8
1
const nextFunction = (req, res) => {
2
//do stuff with res.locals.custDetail
3
res.status(201).json({
4
status: "success",
5
data: { res.locals.regCust },
6
});
7
}
8