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

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

我在 collection

上保存 document 时遇到此错误

ValidatorError:需要路径 id

这是我的代码 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();
});

尝试保存数据时出现错误。 一个

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

Validation 文档中,它说:

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

而在 Save/Validate Hooks 中,它表示:

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.

所以它会在你的 pre('save') 钩子之前验证并给出错误,因为你没有提供必填字段。你可以通过将pre('save')更改为pre('validate')来解决它。

已编辑沙箱:https://codesandbox.io/s/agitated-lederberg-rth1k

当您保存您的博客文档时,您没有传递 id 字段。

id由mongo自动生成,无需指定。 从 BlogPost 模式中删除 id。 但是如果你想给你自己的 id 然后传递一个唯一的 id。

const BlogPost = new Schema({
  empid: String,
  date: Date
});