Hello, I have the code below where I go to next(with a new error) immediately I encounter a sign-up input in the (req.body) that is not expected, in this case if a user want to input some “role”. The problem is, the below codes after the forEach check run even after I get to the next() with a new AppErro().
exports.signUp = asyncWrapper(async (req, res, next) => {
///////////////////////////////////////////////////////////////////
// CHEKING FOR UNEXPECTED INPUTS
const expected = ['name', 'email', 'password', 'passwordConfirm'];
const reqItems = Object.keys(req.body);
reqItems.forEach((el) => {
if (!expected.includes(el)) {
return next(new AppError(`Input "${el}" not expected!`, 400));
}
});
const userData = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
passwordConfirm: req.body.passwordConfirm,
};
console.log(userData, user); PROBLEM FROM HERE
const user = await User.create(userData);
const token = generateToken(user._id);
res.status(201).json({
status: 'success',
token: token,
data: user,
});
});
I noted it excutes the other code after console login the (userData) but also the the new “const user” from the mongoDB.
This is the input from postman:
{
"name": "test",
"email": "test32@email.com",
"password": "1234",
"passwordConfirm": "1234",
"role": "admin"
}
this is the response(prod error) from postman:
{
"status": "fail",
"sender": "production err: operational",
"message": "Input \"role\" not expected!"
}
however in the console I can log: userData and the new user is actually created as seen here:
{
name: 'test',
email: 'test4@email.com',
password: '1234',
passwordConfirm: '1234'
}
{
name: 'test',
email: 'test32@email.com',
password: '$2a$12$3IZ7DoUK7xbAUqmgVdu5buPJa9sMqlNh/WQb.9NZGc/HG5yNLynWW',
role: 'user', //this is default i did in the schema
passwordChangeDate: 2021-09-30T20:08:49.349Z,
active: true,
date: 2021-09-29T19:08:49.349Z,
_id: new ObjectId("615619543d885feadb7d90cb"),
__v: 0
}
though not with the unexpected “role” field. I thought next() with a parameter stops the rest of the execution until i met this! Please help
Understand that the new user will not have the field but I just want to understand why the “next(new AppError(…))” call does not stop execution of the code below. Thank you