简体   繁体   中英

Password is not allowed nodejs + mongo db

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

在此处输入图片说明

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

validationSchema:Joi.object().keys({ 
    name: Joi.string().required(), 
    ... 
}).unknown(true)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM