【问题标题】:Can´t validate type of data on update/findOneAndUpdate mongoose无法验证更新/findOneAndUpdate mongoose 上的数据类型
【发布时间】:2021-12-15 18:07:13
【问题描述】:

在创建时,验证工作正常,如果缺少必需或错误类型,它将引发验证错误。

但是,当我尝试更新或 findOneAndUpdate 时,它​​只会验证是否缺少任何必需的内容,但不会验证类型。目前我可以将 name 属性更新为一个数字,并且不会发生验证错误。有什么想法吗?

mongoose.set('runValidators', true);
const Post = mongoose.model('Post', {
  nome: {
    type: String,
    required: true,
    trim: true
  },
  email: {
    type: String,
    required: true,
    trim: true
  },
  morada: {
    type: String,
    required: true,
    trim: true
  }
})

module.exports = Post
const update = async (req, res) => {
  try {
    let post = await Post.findOneAndUpdate(req.params, req.body, {new: true});     
    res.json(post)
  } catch (e) {
    res.status(500).json(e)
  }
}

【问题讨论】:

    标签: node.js express mongoose mongoose-schema


    【解决方案1】:

    您需要使用mongoose schema 明确定义Post 模型。类似于以下内容:

    const PostSchema = {
        nome: { type: String, required: true, trim: true},
        email: { type: String, required: true, trim: true},
        morada: { type: String, required: true, trim: true}
    };
    
    const Post = mongoose.model('Post', PostSchema);
    

    如果这不起作用,您可以在架构上使用 pre 函数。 pre 函数允许您在执行某些操作(例如保存)之前运行代码,您可以在其中执行更精细的数据验证等操作。

    例如:

    Post.pre("save", function(next, done) {
        let self = this;
    
        if (invalid) {  // Replace 'invalid' with whatever checking needs to be done
            // Throw an Error
            self.invalidate("nome", "name must be a string");
            next(new Error("nome must be a string"));
        }
    
        next();
    });
    

    【讨论】:

    • 非常感谢您的评论。我无法解决架构的问题。关于 pre 函数,我找不到任何文档显示如何验证更新函数的数据类型的示例。所以我还是完全迷路了。
    • 是的,我确实理解它的概念,但我还是一个初学者,所以我不太明白如何使条件起作用。在您的代码中,我可以用 if (nome !== string) 之类的东西替换无效吗?我不明白如何为模式中的属性编写条件。
    • 你可以试试if (!(nome instanceof String))
    猜你喜欢
    • 2016-11-18
    • 2020-07-11
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 2016-09-13
    • 2017-05-06
    相关资源
    最近更新 更多