如何在MongoDb / NodeJs Express应用程序中注册期间修复'validation failed error'



我试图将用户保存到mongodb数据库使用post请求如下,但我得到了错误:
"错误:用户验证失败:邮件:路径'邮件'是必需的。, pseudo:路径' pseudo '是必需的。, password: Path ' password '是必需的。">

PS:我对Eol进行了编辑,但我的问题/和错误仍然存在。

详细信息错误:

errors: {
mail: ValidatorError: Path `mail` is required.
[...] {
properties: [Object],
kind: 'required',
path: 'mail',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},

my controller:

exports.signup = (req, res, next) => {
const user = new User({
mail: req.body.mail,
password: req.body.password,
pseudo: req.body.pseudo,
});
user
.save()
.then(() => res.statuts(201).json({ message: "User created !" }))
.catch(err => console.log(err) )
}

我的用户模型:

const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator"); 
const userSchema = mongoose.Schema({
pseudo: { type: String, required: true, unique: true },
mail: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
userSchema.plugin(uniqueValidator); 
module.exports = mongoose.model("User", userSchema);

My front:

const handleSubmit = (e) => {
e.preventDefault()
const pseudo = e.target[0].value, 
password = e.target[1].value, 
mail = e.target[2].value 
const data = new FormData()
data.set("pseudo", pseudo)
data.set("password", password)
data.set("mail", mail)
axios.post(url, data)
.then(res => console.log(res))
.catch(res => console.log(res))
};
return (
<div>
<form onSubmit={handleSubmit}>
<div >
<label htmlFor="pseudo">Pseudo</label>
<input name="pseudo" type="text" id="pseudo"/>
</div>
<div>
<label htmlFor="password">password</label>
<input name="password" type="password" id="password" autoComplete="true"/>
</div>
<div>
<label htmlFor="mail">email</label>
<input name="mail" type="email" id="mail"/>
</div>
<input
type="submit"
to="/user"
value="Sign up"
/>
</form>
</div>
);
}

您传递给mongoose的对象不包含名为mail的字段,而是将其作为email传递。因此,您需要将email字段从请求有效负载映射到mail:

const user = new User({
mail: req.body.email,
password: req.body.password,
pseudo: req.body.pseudo,
});

您需要修复的另一件事是您的客户端。您正在发送表单数据而不是json-body。改为:

const data = {  pseudo: e.target[0].value, 
password: e.target[1].value, 
mail: e.target[2].value };
axios.post(url, data) // rest of your code

确保您从req.body中获得值。在我看来可能就是这样。尝试在注册控制器中记录req.body的值。新版本的Expressjs不再使用bodyParser中间件,而是使用app.use(express.urlencoded())app.use(express.json())。还不能评论你的帖子,所以这就是为什么这个答案可能是一个建议。

相关内容

  • 没有找到相关文章

最新更新