在mongoose中,如何要求字符串字段不为null或未定义(允许0长度的字符串)?

在mongoose中,如何要求字符串字段不为null或未定义(允许0长度的字符串)?,mongoose,mongoose-schema,Mongoose,Mongoose Schema,我尝试过这种方法,它允许null,未定义,并完全省略要保存的密钥: { myField: { type: String, validate: value => typeof value === 'string', }, } { myField: { type: String, required: true, }, } 这不允许保存''(空字符串): { myField: { type: String, validate

我尝试过这种方法,它允许
null
未定义
,并完全省略要保存的密钥:

{
  myField: {
    type: String,
    validate: value => typeof value === 'string',
  },
}
{
  myField: {
    type: String,
    required: true,
  },
}
这不允许保存
''
(空字符串):

{
  myField: {
    type: String,
    validate: value => typeof value === 'string',
  },
}
{
  myField: {
    type: String,
    required: true,
  },
}

如何在不允许空字符串的情况下,在Mongoose中强制一个字段是一个
字符串
且存在,并且既不是
null
也不是
未定义的

name: {
    type: String,
    validate: {
        validator: function (v) {
            return /^[a-zA-Z]+$/.test(v);
        },
        message: '{PATH} must have letters only!'
    },
},

在模型中尝试此操作,通过使所需字段有条件,可以实现:

const mongoose = require('mongoose');

var userSchema = new mongoose.Schema({
    myField: {
        type: String,
        required: isMyFieldRequired,
    }
});

function isMyFieldRequired () {
    return typeof this.myField === 'string'? false : true
}

var User = mongoose.model('user', userSchema);
这样,
newuser({})
newuser({myField:null})
将抛出错误。但空字符串将起作用:

var user = new User({
    myField: ''
});

user.save(function(err, u){
    if(err){
        console.log(err)
    }
    else{
        console.log(u) //doc saved! { __v: 0, myField: '', _id: 5931c8fa57ff1f177b9dc23f }
    }
})

只需编写一次,它将应用于所有模式

mongoose.Schema.Types.String.checkRequired(v=>typeof v=='String');

请参见&

中的此方法。您现在可以对字符串使用“匹配”属性。match属性采用正则表达式。所以你可以用这样的东西:

myfield: {type: String, required: true, match: /^(?!\s*$).+/}

字符串模式的文档,包括match:

如果我使用它,即使为该属性提供
'
(空字符串)时,也会得到错误
'{PATH}是必需的'
。我已经在我的问题中解决了这个问题(参见我问题中的第二个示例)。是的,您将得到一个错误,因为我们必须输入文本,因为我们已经给出了所需的真实验证,此验证将无效为空字符串或空格。我希望在我的字段上不允许
null
undefined
,但允许任何
string
值,包括空的0长度字符串(
'
)。我的问题还不够清楚吗?这个版本(no
{required:true}
)允许
null
未定义
。我不想这样。也就是说,我需要一个
字符串
值。请尝试更新后的答案。检查它是否能帮助您,否则我建议您在它上面搜索更多内容。我如何在不知道模式将安装在何处的子文档中进行此操作?在
required
callbacks中,
this
始终是父对象,我无法确定如何在回调中找到子文档,而不将其硬编码到错误的位置。您不是在模式中定义子文档吗?对于嵌套字段,它也应该起类似的作用。例如,
返回this.anotherField.nestedField=='string'的类型?false:true
如果我用一种通用的方式编写它,其中我定义了一个模式,比如:
const SubDocSchema=new mongoose.schema({a:{type:String,required:function(){return typeof this.a==='String'}}}})
,那么当我把它作为子文档时,比如
const SuperDocSchema=new mongoose.schema({subDoc{type:SubDocSchema,默认值:SubDocSchema}})
,然后当我尝试验证由
SuperDocSchema
生成的模型实例时,它会检查超级文档而不是子文档的属性
a
,该属性不存在,导致mongoose说子文档的
a
属性是必需的。请参阅更多完整复制:“由于superThing.Undefinedisallowed未定义而引发,即使superThing.thing.Undefinedisallowed为null。"我不知道这是怎么回事。
superThing
中只有一个字段
thing
。所以任何其他字段都应该是未定义的。但是如果我有多个东西使用不同代码中的Mongoose,我无法控制,并且其中一些东西需要默认行为,这会破坏它们。这看起来像是一个经典的例子。@binki在本例中,这是解决方案毫无帮助。然而,在其他情况下,这是一个完美的解决方案