Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

getting error ValidatorError: Path `id` is required. in mongo DB


I am getting this error while saving my document on collection

ValidatorError: Path id is required.

here is my code https://codesandbox.io/s/lively-tree-hd0fo

const BlogPost = new Schema({
  id: { type: String, required: true, unique: true },
  empid: String,
  date: Date
});

BlogPost.pre("save", function(next) {
  var blog = this;
  console.log();
  var data = `${blog.empid}-${blog.date}`;
  blog.id = crypto
    .createHash("md5")
    .update(data)
    .digest("hex");
  next();
});

getting the error when I am trying to save data. a

pp.get("/saveData", async () => {
  try {
    var blog = new BlogPostModel({
      empid: "test123",
      date: "19-Jul-2019"
    });
    console.log("before save");
    let saveBlog = await blog.save(); //when fail its goes to catch
    console.log(saveBlog); //when success it print.
    console.log("saveBlog save");
  } catch (error) {
    console.log(error);
  }
});

Solution

  • In Validation docs, it says:

    Validation is middleware. Mongoose registers validation as a pre('save') hook on every schema by default.

    And in Save/Validate Hooks, it says:

    The save() function triggers validate() hooks, because mongoose has a built-in pre('save') hook that calls validate(). This means that all pre('validate') and post('validate') hooks get called before any pre('save') hooks.

    So it will validate before your pre('save') hook and give the error because you didn't provide the required field. You can solve it by changing pre('save') to pre('validate').

    Editted sandbox: https://codesandbox.io/s/agitated-lederberg-rth1k