【问题标题】:Mongoose how to validate type and value when update/findOneAndUpdateMongoose 如何在更新/findOneAndUpdate 时验证类型和值
【发布时间】:2016-11-18 03:40:33
【问题描述】:

我已经设置了这样的架构。

它在创作上运行良好。如果缺少必需的或错误的类型,它将引发验证错误。所以它会检查类型和值(如果我添加额外的验证函数来验证每个字段上的值)

但是,当我尝试更新或 findOneAndUpdate 时。我已将 runValidators 设置为 true。它以某种方式工作,但它只会验证是否缺少任何必需的内容。但它没有验证类型,可能会自动将我的类型转换为格式。

例如,如果我将 isAction(预期为布尔值)设置为整数,它将自动转换为布尔值 false。所以它有点绕过类型验证。然后它将进入已经是布尔值的验证器函数,但我希望它应该在进入验证函数之前对类型抛出验证错误

另一个问题是数组和对象。它没有验证对象中的深层属性的类型,而是直接进入验证函数。

所以我想看看在更新/findOneAndUpdate 时是否有更好的方法来正确验证类型和值。

我已经搜索了一些 mongoose 验证器模块,但它们中的大多数都是每个字段的验证功能的助手。所以这些数据已经从整数转换为布尔值,并且无法检查当时的类型。

此时,我只能想到在插入/更新到猫鼬之前验证类型和值。

  const schema = new mongoose.Schema({{
    id: {
      type: String,
      unique: true,
      required: true,
    },
    address: {
      formatted: String,
      streetAddress: String,
      locality: String,
      region: String,
      postalCode: String,
      country: String,
    },
    isActive: Boolean,
  });

const user = mongoose.model('User', schema);

// this one work with the validation on the type
User.create({ id : 'userA' }, (err) => {
  console.log(err);
});

// fail to validate the type on both findOneAndUpdate
User.update({ id:'userA'},{ $set: { address:12313 }}, { runValidators: true}, (err) => {
  console.log(err);
});

【问题讨论】:

    标签: node.js mongodb validation mongoose schema


    【解决方案1】:

    本文https://www.mongodb.com/blog/post/introducing-version-40-mongoose-nodejs-odm详细讨论了猫鼬验证器。

    请查看 Pre 和 Post Hooks for Queries 部分,其中列出了 Mongoose 4 功能 pre 和 post hooks 的 count()、find()、findOne()、findOneAndUpdate()、和更新()。

    希望对你有帮助!!

    【讨论】:

    • 但是 pre,post 钩子的上下文是模型本身。即使我们可以获得查询,但我需要手动检查和验证我希望猫鼬根据模式定义的数据类型自动执行的数据类型,并且其行为就像创建一个新的一样。如果是这样,为什么不在手动更新数据之前自己执行验证。顺便说一句,谢谢你的帮助。
    • 我在检查和验证更新时的数据类型方面面临同样的问题。你是如何解决这个问题的?非常感谢!
    猜你喜欢
    • 2021-12-15
    • 2020-08-26
    • 2021-01-02
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 2017-05-06
    • 1970-01-01
    相关资源
    最近更新 更多