0

I am creating a web api with node js and mongodb. i have tried to create a route and when i check it with the postman it says

"password" is not allowed

Here is the code I have Used

for the route

router.post('/adminregister', upload.single('profileImage'), async(req, res) => {

const { error } = registerValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);

const emailExists = await User.findOne({ email: req.body.email });
if (emailExists) return res.status(400).send('Email Already Exists');

const user = new User({
    name: req.body.name,
    gender: req.body.gender,
    bday: req.body.bday,
    email: req.body.email,
    phone: req.body.phone,
    image: req.file.path,
    password: req.body.password
});
try {
    const savedUser = await user.save();

    const token = jwt.sign({ _id: user._id }, process.env.TOKEN_SECRET);

    res.header('auth-token', token).send({
        loginstatus: 'olduser',
        token: token
    });
} catch (err) {
    res.status(400).send(err);
}});

This is the user Schema

const userSchema = new mongoose.Schema({
name: {
    type: String,
    required: true,
    min: 5
},
gender: {
    type: String,
    required: true
},
bday: {
    type: Date,
    required: true
},
email: {
    type: String,
    required: true,
    max: 255,
    min: 6
},
phone: {
    type: String,
    required: true,
    min: 6
},
image: {
    type: String
        // required:true
},
password: {
    type: String
},
usertype: {
    type: String,
    default: 'user'
},
status: {
    type: String,
    required: true,
    default: 'active'
}});

When I do a request though postman it gives me this

but when I remove the password from postman it works fine

enter image description here

Suthura Sudharaka
  • 643
  • 10
  • 25
  • 2
    Post the code for `registerValidation` – Muhammad Zeeshan Jan 26 '20 at 17:15
  • are you using joi validation ? – Saurabh Mistry Jan 26 '20 at 17:18
  • yes @SaurabhMistry but I did not write code to validate password `const registerValidation = data => { const schema = { name: Joi.string().min(6).required(), gender: Joi.required(), bday: Joi.required(), email: Joi.string().min(4).email(), phone: Joi.string().min(5) } return Joi.validate(data, schema);}` – Suthura Sudharaka Jan 26 '20 at 17:22
  • Does this answer your question? [How to allow any other key in Joi](https://stackoverflow.com/questions/49897639/how-to-allow-any-other-key-in-joi) – SuleymanSah Jan 26 '20 at 17:32

2 Answers2

2

add unknown(true) to your Joi schema , to allow other keywords in request body

validationSchema:Joi.object().keys({ 
    name: Joi.string().required(), 
    ... 
}).unknown(true)
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
1

In joi if you haven't added password, it will not allow it. You need pass options

options: {
    allowUnknown: true
  }

to make it work while calling Joi.validate method.

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35