首页 > 解决方案 > 密码不允许 nodejs + mongo db

问题描述

我正在使用节点 js 和 mongodb 创建一个 web api。我试图创建一条路线,当我与邮递员核对时,它说

不允许使用“密码”

这是我用过的代码

对于路线

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);
}});

这是用户架构

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'
}});

当我通过邮递员提出请求时,它给了我这个

但是当我从邮递员那里删除密码时,它工作正常

在此处输入图像描述

标签: javascriptnode.jsmongodbapimongoose

解决方案


添加unknown(true)到您的 Joi 架构中,以允许请求正文中的其他关键字

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

推荐阅读