Node.js “如何修复”;用户验证失败:密码:路径`password`是必需的,电子邮件:路径`email`是必需的,名称:路径`name`是必需的。”;
我是一个初学者,开始学习node.js。在途中,我遇到了一个问题,像这样的通知Node.js “如何修复”;用户验证失败:密码:路径`password`是必需的,电子邮件:路径`email`是必需的,名称:路径`name`是必需的。”;,node.js,nodes,validationerror,Node.js,Nodes,Validationerror,我是一个初学者,开始学习node.js。在途中,我遇到了一个问题,像这样的通知 { "errors": { "password": { "name": "ValidatorError", "message": "Path `password` is required.", "properties": {
{
"errors": {
"password": {
"name": "ValidatorError",
"message": "Path `password` is required.",
"properties": {
"message": "Path `password` is required.",
"type": "required",
"path": "password"
},
"kind": "required",
"path": "password"
},
"email": {
"name": "ValidatorError",
"message": "Path `email` is required.",
"properties": {
"message": "Path `email` is required.",
"type": "required",
"path": "email"
},
"kind": "required",
"path": "email"
},
"name": {
"name": "ValidatorError",
"message": "Path `name` is required.",
"properties": {
"message": "Path `name` is required.",
"type": "required",
"path": "name"
},
"kind": "required",
"path": "name"
}
},
"_message": "User validation failed",
"message": "User validation failed: password: Path `password` is required., email: Path `email` is required., name: Path `name` is required."}
这是我的用户模型
const mongoose = require('mongoose')
const validator = require('validator')
const User = mongoose.model('User', {
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
password:{
type: String,
required: true,
minlength: 7,
trim: true,
validate(value){
if (value.toLowerCase().includes('password')) {
throw new Error('Password cannot contain "password"')
}
}
},
age: {
type: Number,
default: 0,
validate(value) {
if (value < 0 ){
throw new Error('Age must be a positive number')
}
}
}
})
module.exports = User
有人知道为什么会这样吗
希望我在这个论坛上得到答案,继续我的学习。提前感谢你们的帮助。非常感谢。因为您已经按要求定义了所有这些字段:在您的模式中为true,这就是它发生的原因,您必须为这些字段提供值,也就是说,在测试api时,请在正文中用一些值填充这些字段。因为您已经按要求定义了所有这些字段:在您的模式中为true,这就是它发生的原因,您必须为这些字段提供值,也就是说,在测试api时,请在正文中用一些值填充这些字段。在发送之前的“邮递员”中,先更改为“正文”,然后更改为“原始”模块,在“文本”结尾处,更改为“JSON”,这样代码才能工作。在发送之前的“邮递员”中,先更改为“正文”,然后更改为“原始”模块,在“Text”的结尾处,更改为“JSON”,这样您的代码就可以工作了。对不起,我不确定这里是否有相关性。这篇报道没有提到任何关于邮递员的事。他们后端的验证库似乎有问题。对不起,我不确定这里的相关性。这篇报道没有提到任何关于邮递员的事。这似乎是其后端的验证库有问题。
const express = require('express')
require('./db/mongoose')
const User = require('./models/user')
const Task = require('./models/task')
const app = express()
const port = process.env.PORT || 3000
app.use(express.json())
app.post('/users', async (req, res) => {
const user = new User(req.body)
try{
await user.save()
res.status(201).send(user)
} catch (e) {
res.status(400).send(e)
}
})
app.listen(port, () => {
console.log('Server is up on port' +port)
})