【问题标题】:Validations using Mongoose models使用 Mongoose 模型进行验证
【发布时间】:2017-12-01 18:52:13
【问题描述】:

我有一个关于 Mongoose 模型验证的问题。我觉得它们没那么有用。

当我创建一个新模型时,我的代码是

const model = new Comment(commentJson);
const error = model.validateSync();
assert.ok(error, error.errors);

在创建新数据时,验证有点用处。但请考虑更新现有模型的代码。

Comment.findByIdAndUpdate(id, commentJson);

使用上面的代码,我没有机会进行模型验证。我可以检索当前模型,使用 commentJson 更新它,然后对模型进行验证。但是代码看起来有点难看。

相反,我更倾向于编写自己的断言语句,而不是依赖猫鼬验证。有没有办法用猫鼬进行验证而不需要两次访问数据库进行更新?谢谢。

【问题讨论】:

  • 可能是更新前的钩子会有所帮助

标签: mongodb validation mongoose


【解决方案1】:

我会用这个:

try {
  let updatedComment = await Comment.findByIdAndUpdate(
    id, 
    commentJson, 
    {
      new: true,
      runValidators: true
    }
  );

  // Deal with result.
  console.log(updatedComment);
} catch (err) {
  // Deal with error.
  console.log(err);
}

当 Mongoose 更新文档时,它将针对模型的架构运行验证。如果验证失败,catch 块将处理它。

如果您愿意,也可以使用回调:

Comment.findByIdAndUpdate(
  id, 
  commentJson, 
  {
    new: true,
    runValidators: true
  }, (err, updatedComment) => {
    if (err) throw err;

    console.log(updatedComment);
  }
);

Mongoose 通常在调用 save()create() 时自动运行验证器。我认为我以前没有见过很多人手动运行验证器。对于更新功能,验证器默认关闭。设置runValidators: true 将打开它们。请参阅herehere

【讨论】:

  • 谢谢。这真的很整洁。
猜你喜欢
  • 2012-03-02
  • 1970-01-01
  • 1970-01-01
  • 2016-12-24
  • 2017-02-20
  • 2018-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多