Validating req.params with express validator
Params are parsed as string
by express middleware. Say I make a req to path defined below like /some/1000
app.get('/some/:path', (req, res, next) => { console.log(typeof req.param.path) // outputs string})
So you need to parse the incoming parameter to integer (Number) since you've stored accountNumber
as integer. So adding toInt
to chain like below should solve it:
const validateReq: [ param('accountNumber').exists().toInt().custom(acctNo => accountNumberExist(acctNo)),]
accountNumber inside accounts array is a number whereas req.params.accountNumber is a string. You need to convert the data type. You can do it as
accountNumberExist(inputAcct) { const isfound = accounts.find(account => account.accountNumber.toString() === inputAcct); if (isfound === undefined) throw new Error('Account Number not found'); }
I think that the problem is your query. find
method runs in an asynchronous way, that's why isfound
property does not contain the data you expect. Here is a simple approach using promises
which works pretty well for me.
// Here is your function.accountNumberExist(inputAcct) { return accounts.find({accountNumber: inputAcct}) .then(result => { if (result.length == 0) { console.log("Account Number not found"); return Promise.reject('Account Number not found'); } return Promise.resolve(); });}