Mongoose: 유효성 검사 오류 경로가 필요합니다.
새 mongoose mongodb가 .ValidationError: Path 'email' is required., Path 'passwordHash' is required., Path 'username' is required.
이메일, 비밀번호 해시 및 사용자 이름을 제공하고 있지만,
다음은 사용자 스키마입니다.
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
});
이렇게 사용자 개체를 만들고 저장합니다.
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 });
동일한 문제에 대한 해결책을 찾고 있을 때 우연히 이 게시물을 발견했습니다. - 신체에 값이 전달되었음에도 불구하고 유효성 검사 오류입니다.내가 시체를 잃어버린 것으로 밝혀졌어 파서
const bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({ extended: true }));
바디 파서는 익스프레스 최신 버전에 포함되어야 했기 때문에 처음에는 포함하지 않았습니다.위의 두 줄을 추가하여 검증 오류를 해결했습니다.
자, 다음 방법은 제가 오류를 제거한 방법입니다.저는 다음과 같은 스키마를 가지고 있었습니다.
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,
});
그리고 내 단말기는 나에게 다음 로그를 던지고 내 레지스터 기능을 호출할 때 무한 다시 로드됩니다.
되지 않은 약속(예:6676) 거부 파일: 되지 않은 거부 ID: 오류: 비밀번호:: 경로: ID: 1): 처리되지 않은 약속 거부: 오류:
password
필수 항목입니다. 파일: 이메일입니다.잘못된 이메일입니다.(노드:6676) [DEP0018] 사용 중지 경고:처리되지 않은 약속 거부는 더 이상 사용되지 않습니다.앞으로 처리되지 않는 약속 거부는 0이 아닌 종료 코드로 Node.js 프로세스를 종료합니다.
그래서 경로 '비밀번호'가 필요하다고 쓰여있었기 때문에, 저는 다음과 같이 언급했습니다.required:true
과 내모에을그리고인라서델▁out▁line.validate:email
내 모델에서 라인 아웃.
기본적으로 이 작업을 올바르게 수행하고 있지만 부트스트랩이나 다른 라이브러리 요소를 추가하면 이미 검증자가 있습니다.따라서 에서 검증자를 제거할 수 있습니다.
여기서 전화 속성에서 "required:true"는 부트스트랩 및 기타 라이브러리/의존성에서 이미 확인되었기 때문에 제거할 수 있습니다.
var userSchema = new Schema({
name: {
type: String,
required: 'Please enter your name',
trim: true
},
phone: {
type: number,
required: true
} });
동일한 오류가 발생했기 때문에 모델에 필요한 모든 필드를 수행했습니다. 해당 필드가 서비스의 새 사용자 Obj에 나타나는지 또는 사용자의 서비스가 있는 모든 위치에 나타나는지 확인해야 했습니다.
const newUser = new User({
nickname: Body.nickname,
email: Body.email,
password: Body.password,
state: Body.state,
gender:Body.gender,
specialty:Body.specialty
});
우체부와 일할 때는 본문을 전송했는지 확인해야 합니다.>raw>>JSON 유형(나의 경우 JSON이 아닌 Text)
나에게 빠르고 더러운 해결책은 제거하는 것이었습니다.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.
전자 메일이 스키마에서 필수로 설정되었지만 값이 지정되지 않았거나 전자 메일 필드가 모델에 추가되지 않았습니다.
이메일 값이 비어 있을 수 있는 경우 모델에서 기본값을 설정하거나 유효성 검사에서 allow(""")를 설정합니다.맘에 들다
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());
그리고 그것은 제대로 작동해야 합니다.
언급URL : https://stackoverflow.com/questions/31663665/mongoose-validation-error-path-is-required
'programing' 카테고리의 다른 글
Git 기록에서 중요한 파일 및 해당 커밋 제거 (0) | 2023.05.21 |
---|---|
서로 다른 값 유형 간의 0으로 나누기 동작 불일치 (0) | 2023.05.21 |
특정 파일에 대한 변경 사항만 선택하는 방법은 무엇입니까? (0) | 2023.05.21 |
OSX 10.7 Lion으로 업그레이드한 후 Postgresql 복구 (0) | 2023.05.21 |
Node.js 프로젝트의 폴더 구조 (0) | 2023.05.21 |