-1

I am getting an error that Cannot read property 'string' of undefined however i downloaded the joi module npm i @hapo/joi. i don't understand what is the error is about.

it refers to this part of code in the validation file

username: joi.string().min(6).required(),

here is the callback function for the post request /create-user

The requiring modules

    const expressValidator = require('express-validator');
const bycrypt = require('bcryptjs');

const bodyparser = require("body-parser"); //requiring the body parser     

const passport = require('passport');

const flash = require('express-session');

//import the validation file 

const userValidation = require('./validation');

exports.createUser = async(req, res, next) => {

console.log('Post CREATE User /create-user');

//validation the user 
const { error } = userValidation(req.body);

//if the req.body didn't pass the vaildation part 
if (error) {
    return res.status(400).send(error.details[0].message);
}

//one of the solutions

  try {
    //checking if the user is already exist 

    const userExist = await userSchema.findOne({ username: req.body.username });

    if (userExist) return res.status(400).send('UserName Already Exist');
} catch (error) {
    console.log(error);
}

//Hashing The Password


const salt = await bycrypt.genSalt(10);

const hashedPassword = await bycrypt.hash(req.body.password, salt);


// creating a new user from the schema 

const user = new userSchema({
    username: req.body.username,

    password: req.body.hashedPassword
})

// saving the user inside the db

user
    .save()
    .then(data => {
        res.redirect('/halalMunchies/all-employees');
    })
    .catch(err => {
        res.status(500).send({
            message: err.message || "Some error occured while creating a create operation"
        });
    });

};

the validation file which it exist at the same folder with the call back function, this to validate user's input

 //validation

const joi = require('joi');

//creating user Schema validation 

const userValidation = (data) => {

    const schema = {

        username: joi.string().min(6).required(),

        password: joi.string().min(6).required()

    };

    return joi.valid(data, schema);

};

//creating login Schema validation 

const loginValidation = (data) => {

    const schema = {

        username: joi.string().min(6).required(),

        password: joi.string().min(6).required()

    };

    return joi.validate(data, schema);

};

//export

module.exports.userValidation = userValidation;
module.exports.loginValidation = loginValidation;

THE ERROR

 (node:5720) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'string' of undefined
    at userValidation (E:\HalalMunchies\server\controller\validation.js:11:23)
    at exports.createUser (E:\HalalMunchies\server\controller\usersController.js:32:23)
    at Layer.handle [as handle_request] (E:\HalalMunchies\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\HalalMunchies\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (E:\HalalMunchies\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (E:\HalalMunchies\node_modules\express\lib\router\layer.js:95:5)
    at E:\HalalMunchies\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (E:\HalalMunchies\node_modules\express\lib\router\index.js:335:12)
    at next (E:\HalalMunchies\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (E:\HalalMunchies\node_modules\express\lib\router\index.js:174:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:5720) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:5720) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js 
process with a non-zero exit code.

// the changes

install the joi

npm install joi

in the validation.js, instead of joi.validate i used joi.valid. no errors in the log but when i tried to add a user i didn't add and it shows an error on the page {"message":"userSchema validation failed: password: Path password is required."}

    //validation

const joi = require('joi');



//creating user Schema validation 

const userValidation = (data) => {

    const schema = joi.object({

        username: joi.string().min(6).required(),

        password: joi.string().min(6).required()

    });

    return joi.valid(data, schema);

};

// the ejs file form top

<form action="/halalMunchies/create-user" method="post">

    <div class="form-group">
        <label class="control-label" for="username"> Username </label>
        <input id="username" class="form-control" name="username" required autofocus="autofocus" />
    </div>
 <div class="form-group">
        <label class="control-label" for="password"> Password  </label> <input id="password" class="form-control" name="password" required autofocus="autofocus" type="password" />
    </div>

    <div class="form-group">
        <label class="control-label" for="password2"> confirm Password  </label> <input id="password2" class="form-control" name="password2" required autofocus="autofocus" type="password" />
    </div>



    <div class="form-group">
        <button type="submit" class="btn btn-success">Add User</button>
    </div>
</form>

1 Answer 1

1

This:

const {joi} = require('@hapi/joi');

should be this:

const joi = require('@hapi/joi');

You can't "guess" how the import works. You need to look at the documentation and see exactly how you are supposed to import the library. In this case, the entire exports object is the joi object so there's no .joi property on it.

See the example in the documentation here.

4
  • okay i looked at it and i did some changes but lead to another error but i think they all related coz the password didn't check. i will add all the updates now Nov 14, 2021 at 4:24
  • @HeshamEldawy - Just so you understand. At stackoverflow, you ask a specific question and solicit answers for that specific question. If when you apply a suggested fix that error goes away, but it leads to another error in need of a different fix, then you don't edit your question to include that new error. If, after attempting some debugging yourself on the new error, you still can't figure it out, then you write a new question from scratch about the new error.
    – jfriend00
    Nov 14, 2021 at 5:02
  • Hi @jfriend00 could u plz help me with this problem stackoverflow.com/q/70037304/15454800 Nov 20, 2021 at 11:07
  • @HeshamEldawy - Databases are not my area of knowledge.
    – jfriend00
    Nov 20, 2021 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.