保存猫鼬数组模式类型时忽略空值或空值

时间:2020-01-26 05:30:26

标签: node.js mongodb mongoose

我有以下架构:

const userSchema = new mongoose.Schema({
    email: [{
        type: String,
        trim: true,
     }]
})

保存新用户时,

const user = new User({
    email: ["example@example.com", ""]
    //or email: ["example@example.com", null]
})

try{
   await user.save()
} catch (e) {
   console.log(e)
}

这将保存两个值(分别包括空字符串和null)。

有没有一种方法可以只保留正确的电子邮件值,而丢弃空值或null值。 代替此:

"email" : [ 
        "example@example.com", 
        ""
    ],

仅存储正确的电子邮件:

"email" : [ 
        "example@example.com", 
    ],

当前,对于其他架构字段,我正在使用set。例如,在上面的用户架构中

url: {
    type: String,
    set: deleteEmpty
}



const deleteEmpty = (v) => {
  if(!v) {
      return undefined
  }

  return v
}

当然,如果值为空或为null,则根本不会保存url字段。 但是,在上面的电子邮件字段上使用此方法将生成一个空值。

是否可以仅存储正确的电子邮件值(在这种情况下,即“ example@example.com”,而忽略空值或空值)?

4 个答案:

答案 0 :(得分:2)

?‍? 我认为,您可以使用userSchema在below下面使用类似以下代码的代码:

userSchema.pre('save', function(next) {
  this.email = this.email.filter(email => email);
  next();
})

☝️上面的代码将忽略数组中的所有emptynull值。你可以试试看。

第二个选项,您可以在required的{​​{1}}字段中添加email。看起来很像下面的代码:?

userSchema

?☝️上方的代码,如果在数组上传递空字符串,将给您一个错误

希望它能对您有所帮助。

答案 1 :(得分:0)

您可以执行以下操作来实现所需的目标。

var arr = ['example@example.com', '']; // variable to keep the an array containing values

var i;
for (i = 0; i < arr.length; i++) {
  if (arr[i] == null || arr[i] == '') {
    arr.slice(i); // remove null or '' value
  }
}

console.log('normalized array: ', arr);
// schema code
const user = new User({
    email: arr
})

try{
   await user.save()
} catch (e) {
   console.log(e)
}

祝你好运,我希望我回答了你的问题。

答案 2 :(得分:0)

如果任何人都有一个或多个具有数组值的字段并想要检查每个字段,我建议在pre save钩子上使用中间件。

supplierSchema.pre('save', normalizeArray)


const normalizeArrray = function(next) {

    //take the list of object feilds and for each field check if it is array
    Object.keys(this.toObject()).forEach((field) => {

        if(Array.isArray(this[field])) {

            //removes null or empty values
            this[field] = this[field].filter(field => field)
        }
    })

    next()
}

这只是基于上面已经批准的答案。

答案 3 :(得分:0)

只需将要忽略的字段的默认值(如果为空)设置为 undefined。此外,将 required 设置为 false

使用以下代码:

const userSchema = new mongoose.Schema({
    email: [{
        type: String,
        trim: true,
        required: false,
        default: undefined
     }]
})