【问题标题】:Password is not allowed nodejs + mongo db密码不允许 node js + mongodb
【发布时间】:2020-05-12 05:10:28
【问题描述】:

我正在使用 node 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'
}});

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

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

【问题讨论】:

  • 发布registerValidation的代码
  • 你在使用 joi 验证吗?
  • 是的@SaurabhMistry,但我没有编写代码来验证密码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);}
  • 这能回答你的问题吗? How to allow any other key in Joi

标签: javascript node.js mongodb api mongoose


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    joi中如果没有添加password,是不允许的。你需要通过选项

    options: {
        allowUnknown: true
      }
    
    

    在调用Joi.validate 方法时使其工作。

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2011-08-25
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多