Search code examples
node.jsexpressexpress-sessionexpress-validator

Express.js - Adding custom object to req.session.errors


I am using express-validators and express-session to work with my forms.

in index.js : I redirect to /inscription with errors as an object to show the errors above the fields. It works great.

router.post('/submit-inscription', function (req, res, next) {
req.check('mail', 'Invalid Mail Address').isEmail();
var errors = req.validationErrors();
if (errors) { 
req.session.errors = errors;
req.session.success = false;
res.redirect('/inscription');
}

But then if there is no error, I check if the mail entered doesnt already exists in my my mongodb.

If it does already exist, I would like to redirect to /inscription with a special error. I could do this using a new session parameter, but I would like to do it using the same errors session.

So I tried :

else { // email already used
error = {location: 'body', msg:"Email address already registered", param:'mail', value:''};
errors.push(error);
req.session.errors = errors;
res.redirect('/inscription');
}

The error I get is : errors.push is not a function. I guess it is because errors is not an array but an object.

So my question is how could I add this custom error to my req.session.errors object ?


Solution

  • After a discussion with Sohail, thanks a lot to him, he helped me discover from where and how to solve it.

    let error = {location: 'body', msg:"Email address already registered", param:'mail', value:''};
    req.session.errors = [error];
    res.redirect('/inscription');