Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
253 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...