猫鼬部分验证

时间:2018-11-07 09:37:02

标签: node.js mongodb mongoose

我有这种猫鼬模式

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Person = new Schema({
first_name: {
    type: String,
    required:true
},
last_name: {
    type: String,
    required:true
},
dob: {
    type: Date
},
phone: {
    type: String
},
email: {
    type: String,
    required:true
},
address: {
    type: String,
    required:true
},
city: {
    type: String
},
state: {
    type: String
},
zipCode: {
    type: Number
}
});
module.exports = mongoose.model("Person", Person);

我的App用户需要填写2个表格以获取此信息。诸如first_name,last_name,dob,phone之类的一半信息将采用第一种形式。我必须先保存此信息,然后再移至第二个表单,在第二个表单上,我有电子邮件,地址,城市,州,邮政编码。

但是当我保存第一个表格时。这将给我错误,因为电子邮件是必需的,并且是第二种形式。

那么如何使用猫鼬验证对象中的某些字段?

还是有其他解决方案?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以在必填字段上使用函数,以测试first_name字段是否为空,否则,电子邮件字段不是必需的。

类似这样的东西:

const Person = new Schema({
first_name: {
    type: String,
    required:true
},
last_name: {
    type: String,
    required:true
},
dob: {
    type: Date
},
phone: {
    type: String
},
email: {
    type: String,
    required: () => this.first_name != null
},
address: {
    type: String,
    required: () => this.first_name != null
},
city: {
    type: String
},
state: {
    type: String
},
zipCode: {
    type: Number
}
});

Documentation