为什么Mongoose不验证空文档? [英] Why Mongoose doesn't validate empty document?

查看:78
本文介绍了为什么Mongoose不验证空文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个非常简单的架构,其中包含一个自定义验证功能,该功能始终返回false.

Let's say I have a very simple schema with a custom validation function that always returns false.

var MofoSchema = new mongoose.Schema({
  name: String
});

MofoSchema.path('name').validate(function (value) {
  console.log("I'm validating");
  return false;
}, 'No pasaran');

mongoose.model('Mofo', MofoSchema);

然后,我创建我的文档的新实例并对其进行验证:

Then I create a new instance of my document and I validate it:

var Mofo = mongoose.model('Mofo');
var mofo = new Mofo({name: "Tarte flambée"});

mofo.validate(function(err) {
  console.log(err);
});

完美,将调用自定义验证程序函数并填充err.

Perfect, the custom validator function is called and err is filled.

但是现在我做同样的没有数据:

var Mofo = mongoose.model('Mofo');
var mofo = new Mofo({});

mofo.validate(function(err) {
  console.log(err);
});

未调用自定义验证器功能,并且未定义err. 为什么?我不明白为什么猫鼬没有运行自定义验证器.

The custom validator function is not called and err is undefined. Why? I don't understand why Mongoose is not running the custom validator.

这是设计使然吗?是虫子吗? 我应该改掉吗?验证之前,我应该手动检查是否有空数据吗?

Is this behaviour by design? Is it a bug? Should I hack a turnaround? Should I check manually for empty data before validation?

我做错什么了吗?

PS:如果调用save,则尽管有自定义验证程序,该文档仍将在MongoDB中保存为空.

PS: If you call save, the document will be saved as empty in MongoDB despite of the custom validator.

推荐答案

我认为猫鼬只会对现有字段进行验证.

I think mongoose will only validate for existing field.

因此您可以使用'null'值来激活验证

So you can use 'null' value to activate validation

var mofo = new Mofo({name: null});

用于空白或未定义

var MofoSchema = new mongoose.Schema({
  name: {type: String, required: true}
});

MofoSchema.path('name').validate(function (value) {...}, 'no pasaran');

这篇关于为什么Mongoose不验证空文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆