Mongoose:需要验证错误路径
Mongoose: validation error path is required
我试图在mongodb与mongoose保存一个新文档,但我得到ValidationError: Path 'email' is required., Path 'passwordHash' is required., Path 'username' is required.
即使我提供电子邮件,passwordHash和用户名。
用户模式
var userSchema = new schema({
_id: Number,
username: { type: String, required: true, unique: true },
passwordHash: { type: String, required: true },
email: { type: String, required: true },
admin: Boolean,
createdAt: Date,
updatedAt: Date,
accountType: String
});
这是我创建和保存user对象的方法。
var newUser = new user({
/* We will set the username, email and password field to null because they will be set later. */
username: null,
passwordHash: null,
email: null,
admin: false
}, { _id: false });
/* Save the new user. */
newUser.save(function(err) {
if(err) {
console.log("Can't create new user: %s", err);
} else {
/* We succesfully saved the new user, so let's send back the user id. */
}
});
那么为什么mongoose返回验证错误,我可以不使用null
作为临时值吗?
回复你上次的评论。
你是正确的,null是一个值类型,但是null类型是告诉解释器它有没有值的一种方式。因此,必须将这些值设置为任何非空值,否则就会出现错误。在这种情况下,将这些值设置为空字符串。例如
var newUser = new user({
/* We will set the username, email and password field to null because they will be set later. */
username: '',
passwordHash: '',
email: '',
admin: false
}, { _id: false });
当我在寻找解决同样问题的方法时,我遇到了这篇文章——即使值被传递到body中也会出现验证错误。原来我漏掉了bodyParser
const bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({ extended: true }));
我最初没有包含bodyParser,因为它应该包含在express的最新版本中。添加以上两行解决了验证错误。
好吧,下面是我如何消除错误的方法。我有以下模式:
var userSchema = new Schema({
name: {
type: String,
required: 'Please enter your name',
trim: true
},
email: {
type: String,
unique:true,
required: 'Please enter your email',
trim: true,
lowercase:true,
validate: [{ validator: value => isEmail(value), msg: 'Invalid email.' }]
},
password: {
type: String/
required: true
},
// gender: {
// type: String
// },
resetPasswordToken:String,
resetPasswordExpires:Date,
});
和我的终端向我抛出以下日志,然后在调用寄存器函数时进入无限重新加载:
(node:6676) UnhandledPromiseRejectionWarning:未处理的承诺rejection (rejection id: 1): ValidationError: password: Path
password
是必需的。, email: Invalid email.(node:6676) [DEP0018] DeprecationWarning:未处理的承诺拒绝弃用。在将来,承诺未处理的拒绝将以非零退出码终止Node.js进程。
所以,因为它说路径'密码'是必需的,我把required:true
行从我的模型和validate:email
行从我的模型中注释出来。
基本上,您这样做是正确的,但是如果您添加bootstrap或任何其他库元素,它们已经具有验证器。因此,您可以从userSchema
中删除验证器。
这里,在电话属性中,你可以删除"required: true"因为它已经在bootstrap和其他库/依赖项中检查过了。
var userSchema = new Schema({
name: {
type: String,
required: 'Please enter your name',
trim: true
},
phone: {
type: number,
required: true
} });
我遇到了同样的错误所以我所做的是我在模型中需要的任何字段我必须确保它出现在新的用户对象中在我的服务中或者你有你的
const newUser = new User({
nickname: Body.nickname,
email: Body.email,
password: Body.password,
state: Body.state,
gender:Body.gender,
specialty:Body.specialty
});
使用Postman时,您应该确保您发送的Body>>raw>>JSON类型(在我的情况下是Text而不是JSON)
对于我来说,快速而肮脏的解决方案是从输入表单字段中删除encType="multipart/form-data"
。
, <form action="/users/register" method="POST" encType="multipart/form-data">
, <form action="/users/register" method="POST">
解决这种类型的错误
ValidationError: Path 'email' is required.
您的电子邮件在模式中设置为必需的,但没有给出值或没有在模型上添加电子邮件字段。
如果您的电子邮件值可能是空的设置默认值在模型或设置允许(")验证。像
schemas: {
notificationSender: Joi.object().keys({
email: Joi.string().max(50).allow('')
})
}
我也遇到了同样的错误
import mongoose from 'mongoose';
const orderSchema = mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
orderItems: [
{
name: { type: String, required: true },
qty: { type: Number, required: true },
image: { type: String, required: true },
price: { type: Number, required: true },
product: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Product',
},
},
],
shippingAddress: {
address: { type: String, required: true },
city: { type: String, required: true },
postalCode: { type: String, required: true },
country: { type: String, required: true },
},
paymentMethod: {
type: String,
required: true,
},
paymentResult: {
id: { type: String },
status: { type: String },
update_time: { type: String },
email_address: { type: String },
},
taxPrice: {
type: Number,
required: true,
default: 0.0,
},
shippingPrice: {
type: Number,
required: true,
default: 0.0,
},
totalPrice: {
type: Number,
required: true,
default: 0.0,
},
isPaid: {
type: Boolean,
required: true,
default: false,
},
paidAt: {
type: Date,
},
isDelivered: {
type: Boolean,
required: true,
default: false,
},
deliveredAt: {
type: Date,
},
},
{
timestamps: true,
}
);
const Order = mongoose.model('Order', orderSchema);
export default Order;
下面是我的终端错误:
消息:"订单验证失败:用户:路径
user
是必需的。"
我所做的只是删除了用户的需求,一切都很好。
我也有同样的问题。原来我导入的是错误的模型。首先检查您的导入。并且不要将null值设置为null,而是将整数设置为-1或将字符串设置为' '
尝试删除名称,用户,发件人任何中的一些必需字段后…像这样……我从发送者那里删除了要求,它工作了
const mongoose = require("mongoose");
const userModel = mongoose.Schema(
{
//sender: { type: String, **required: true** } **from**
sender: { type: String}, **// to**
email: { type: String, required: true, unique: true },
password: {
type: String,
required: true,
default:
"https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg",
},
},
{
timestamps: true,
}
);
const User = mongoose.model("User", userModel);
module.exports = User;
您只需添加app.use(express.json());
,它应该正常工作
- javascript window.location在检查firebug时给了我一个错误的url路径
- 最短路径算法js错误
- AngularFire 0.5美元移除.错误:Firebase.child失败:第一个参数是无效路径
- windows文件系统中的nodejs路径错误4058 ENOENT
- angularjs中的相对href路径与html5mode错误
- Express.js恶意路径中间件错误403
- 错误'路径保留冲突'同时启动流星应用程序
- Require.js在错误的路径中查找嵌套的依赖项
- 火狐插件错误:在 resource://gre/modules/commonjs/http.js 找不到模块“路径”
- 错误:<路径>属性 d=“MNaN,NaNA5,5 0 1,1 NaN,NaNL0,0Z”的值无效
- “错误:命名模块未知”,从动态路径加载反应本机图像
- 使用 JS 更改映像路径的请求错误
- 第一个角度$http POST 落入 .then 错误路径,即使 REST 调用成功
- 节点中的 Web 服务器.js路径中的错误
- 路径错误中的非法字符
- 谷歌地图:- 无效值错误:设置图标:不是字符串;并且没有网址属性;并且没有路径属性
- C3 时间序列图表给出错误 <路径>属性的值无效
- 动态加载TinyMCE - 错误的插件,主题路径
- "错误:路径必须是字符串“”;(v.10.0)
- Mongoose:需要验证错误路径