'Mongoose Returns TypeError: Cannot read properties of null (reading 'name')
I'm working on express-typescript-moongose, where user wanted to verify via email. Mongoose return the following error
TypeError: Cannot read properties of null (reading 'name')
at new CustomError (/app/src/utils/response/error.ts:15:18)
at /app/src/controllers/user.controller.ts:105:25
at Generator.next (<anonymous>)
at fulfilled (/app/src/controllers/user.controller.ts:5:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
on the following query
const result = await User.findOneAndUpdate({
confirmUserToken: req.params.token,
confirmUserExpires: { $gt: new Date() },
status: "pending",
}, {
status: "active",
confirmUserToken: null,
confirmUserExpires: null,
}, {
new: true,
runValidators: true,
rawResult: true,
debug: true,
});
it's working fine on first query, but once user is verified and try to fetch the same query it's started giving the error instead of returning no object found.
try{
const result = await User.findOneAndUpdate({
confirmUserToken: req.params.token,
confirmUserExpires: { $gt: new Date() },
status: "pending",
}, {
status: "active",
confirmUserToken: null,
confirmUserExpires: null,
}, {
new: true,
runValidators: true,
rawResult: true,
debug: true,
});
if(!result.value) {
const err = new CustomError(400, "General", "Token is invalid or expired", null);
return next(err);
}
res.customSuccess(200, "User verified successfully", {user: result.value});
} catch(err){
console.log(err);
const error = new CustomError(500, "Application", "Error while doing some user operation", err);
return next(error);
}
it's working fine when it's find the document, but once this document is modified and try to fetch the same query, instead of returning value===null, it's started giving the error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
