无法验证 update/findOneAndUpdate mongoose 上的数据类型

问题描述 投票:0回答:2

在创建中,验证工作正常,如果缺少必需的或错误的类型,它将抛出验证错误。

但是,当我尝试更新或 findOneAndUpdate 时,它仅验证是否缺少任何必需的内容,但不验证类型。目前,我可以将名称属性更新为数字,并且不会发生验证错误。知道该怎么做吗?

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
2个回答
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();
});

0
投票

我刚刚在这里发布了类似问题的答案:https://stackoverflow.com/a/38388482/66506

也许它会对您的情况有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.