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

bin*_*nki 11 mongoose mongoose-schema

我已经尝试过这个,它允许null,undefined和完全省略要保存的密钥:

{
  myField: {
    type: String,
    validate: value => typeof value === 'string',
  },
}
Run Code Online (Sandbox Code Playgroud)

这不允许''(空字符串)被保存:

{
  myField: {
    type: String,
    required: true,
  },
}
Run Code Online (Sandbox Code Playgroud)

如何在不禁止空字符串的情况下强制一个字段是 aString并且存在并且既不在 Mongoose 中null也不undefined在 Mongoose 中?

Tal*_*wan 13

通过将所需字段设为条件,可以实现:

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);
Run Code Online (Sandbox Code Playgroud)

有了这个,new User({})并且new User({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 }
    }
})
Run Code Online (Sandbox Code Playgroud)


Amj*_*mar 6

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

mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');
Run Code Online (Sandbox Code Playgroud)

请参阅官方 mongoose 文档github 问题中的此方法