简体   繁体   中英

Mongoose: validation error path is required

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?

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. ie

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 });

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.

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.

For me, the quick and dirty fix was to remove encType="multipart/form-data" from my input form field.

Before, <form action="/users/register" method="POST" encType="multipart/form-data">
and, after <form action="/users/register" method="POST">

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.

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.

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
} });

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
});

You Just Simply Add app.use(express.json()); And It Should Work Properly.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM