I have tried creating a controller which will update a specific user’s wallet and save it in the database. When i try to fetch it from the postman using the link:
http://localhost:3001/wallets/{walletID}
=== _id
With the body:
{
"balance": 100
}
And it is showing this 400 error as the result:
{
"hasError": true,
"message": "ERROR: Data Validation Failed.",
"error": {
"error": "'walletId' is required. 'balance' is not allowed."
}
}
And when i try to fetch it in another way with this link:
http://localhost:3001/wallets/{_walletId}
=== specific wallet’s ID
With the same body, It’s showing this 400 status code:
{
"hasError": true,
"message": "ERROR: Data Validation Failed.",
"error": {
"error": "'walletId' contains an invalid value."
}
}
TBH I wasn’t expecting it to be working fine because i have tried it once and the code is generated by Chat.gpt. This is the updateWalletById controller:
/**
* this controller updates specific wallet via walletId & returns it
* @async
* @param {obj} req - incoming request obj
* @param {obj} res - outgoing response obj
* @param {func} next - method to pass control to next request handler in queue
* @returns updated record from database
*/
const updateWalletById = async (req, res, next) => {
try {
const walletId = req.params.walletId; // Fetch walletId from request params
const balance = req.body.balance; // Fetch balance from request body
// Update the balance in the database
const updatedWallet = await Wallet.findByIdAndUpdate(
walletId,
{ balance },
{ new: true }
);
// Check if the wallet was found
if (!updatedWallet) {
return res.status(NOT_FOUND).json({
hasError: true,
message: 'Wallet not found',
});
}
return res.status(SUCCESS).json({
hasError: false,
message: 'Wallet updated successfully',
data: {
wallet: updatedWallet,
},
});
} catch (error) {
logError('ERROR @ updateWalletById -> wallet.controllers.js', error);
return res.status(SERVER_ERROR).json({
hasError: true,
message: 'ERROR: Requested operation failed.',
error: {
error: 'An unexpected error occurred on the server.',
},
});
}
};
I’ve understood the functionality and working of the code, and it seems correct but i’m not getting why is it throwing the error?
A help will be so Gratefull <#
2
Answers
The issue was with the wallets.router.js:
I wasn't passing the
PARAMS
or theauthentication request
. So, I changed the code from this:To this:
In your URL, you are using {walletID} as the parameter, but in the controller, you are using walletId (with a lowercase "d") as the parameter.