Reputation: 1383
I'm trying to save a new document in mongodb with mongoose, but I am getting ValidationError: Path 'email' is required., Path 'passwordHash' is required., Path 'username' is required.
even though I am supplying email, passwordHash and username.
Here is the user schema.
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
});
This is how I am creating and saving the user object.
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. */
}
});
So why does mongoose return a validation error, can I not use null
as temporary value?
Upvotes: 50
Views: 154869
Reputation: 42
commenting out the required field solved mine successfully
const authSchema = mongoose.Schema({
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
validate: [validator.isEmail, 'Please provide a valid email address'],
},
username: {
type: String,
required: [true, 'Username is required'],
unique: true,
},
password: {
type: String,
required: [true, 'Password is required'],
},
confirmPassword: {
type: String,
>>> // required: [true, 'Please confirm your password'],
validate: {
// Custom validator to check if passwords match
validator: function (el) {
return el === this.password;
},
message: 'Passwords do not match',
},
},
});
Upvotes: 0
Reputation: 61
For me, the quick and dirty fix was to remove encType="multipart/form-data"
from my input form field.
Before my code was, <form action="/users/register" method="POST" encType="multipart/form-data">
and, then after i changed it to <form action="/users/register" method="POST">
and that helped me solve the error
Upvotes: 1
Reputation: 568
Try after removing some of your required fields in name, user, sender anything... Like this ... I removed the required from the sender and it worked
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;
Upvotes: 1
Reputation: 1
i had the same problem. turns out i was importing the wrong model. check first your imports. and dont set null values to null, instead set them to -1 for integers or ' ' for strings
Upvotes: 0
Reputation: 37061
When working with Postman you should make sure that you have sending Body>>raw>>JSON type (in my case it was Text instead of JSON)
Upvotes: 3
Reputation: 25
You Just Simply Add app.use(express.json());
And It Should Work Properly.
Upvotes: -2
Reputation: 21
I ran into the same err so what I did is any field I required in my model I had to make sure it appears in the new User Obj in my services or anywhere you have yours
const newUser = new User({
nickname: Body.nickname,
email: Body.email,
password: Body.password,
state: Body.state,
gender:Body.gender,
specialty:Body.specialty
});
Upvotes: 2
Reputation: 203
Basically, you are doing this correctly, but if you add bootstrap or any other library element, they already have validators.
So, you can remove validators from userSchema
.
Here, in phone attributes, you can remove "required: true" because it is already checked in bootstrap and other libraries/dependencies.
var userSchema = new Schema({
name: {
type: String,
required: 'Please enter your name',
trim: true
},
phone: {
type: number,
required: true
} });
Upvotes: 3
Reputation: 197
I also ran into the same error
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;
And below was the error in my terminal:
message: "Order validation failed: user: Path
user
is required."
All I did was to remove required from the user and everything worked fine.
Upvotes: -1
Reputation: 550
To solve this type of error
ValidationError: Path 'email' is required.
your email is set required in Schema, But no value is given or email field is not added on model.
If your email value may be empty set default value in model or set allow("") in validatior. like
schemas: {
notificationSender: Joi.object().keys({
email: Joi.string().max(50).allow('')
})
}
I think will solve this kind of problem.
Upvotes: 0
Reputation: 141
I came across this post when I was looking for resolution for the same problem - validation error even though values were passed into the body. Turns out that I was missing the bodyParser
const bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({ extended: true }));
I did not initially include the bodyParser as it was supposed to be included with the latest version of express. Adding above 2 lines resolved my validation errors.
Upvotes: 10
Reputation: 1591
Well, the following way is how I got rid of the errors. I had the following schema:
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,
});
and my terminal throw me the following log and then went into infinite reload on calling my register function:
(node:6676) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ValidationError: password: Path
password
is required., email: Invalid email.(node:6676) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
So, as it said Path 'password' is required, I commented the required:true
line out of my model and validate:email
line out of my model.
Upvotes: 8
Reputation: 2166
In response to your last comment.
You are correct that null is a value type, but null types are a way of telling the interpreter that it has no value. therefore, you must set the values to any non-null value or you get the error. in your case set those values to empty Strings. i.e.
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 });
Upvotes: 24