在创建中,验证工作正常,如果缺少必需的或错误的类型,它将抛出验证错误。
但是,当我尝试更新或 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)
}
}
您需要使用
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();
});
我刚刚在这里发布了类似问题的答案:https://stackoverflow.com/a/38388482/66506
也许它会对您的情况有所帮助。