Node.js 猫鼬的动态验证

Node.js 猫鼬的动态验证,node.js,mongoose,Node.js,Mongoose,我有一个模型,其中car属性是可选的,但在car嵌套文档中有一些属性,如果用户有car,则应该需要这些属性,比如cartype:{required:true},但当定义了car时 var UserSchema = new Schema({ email: { type: 'String', required: true }, car: { carType: {

我有一个模型,其中car属性是可选的,但在car嵌套文档中有一些属性,如果用户有car,则应该需要这些属性,比如
cartype:{required:true}
,但当定义了car时

 var UserSchema = new Schema({
        email: {
            type: 'String',
            required: true
        },
        car: {
            carType: {
               // should be required if user have car
               type: 'Number',
               default: TransportType.Car
            },
        }
    })

如果
carType
没有
默认值
,我们可以定义
carType
的一个函数
hasCar
必需的
,如下所示

var UserSchema = new Schema({
    email: {
        type: 'String',
        required: true
    },
    car: { 
        carType: {
           type: 'Number',
           required: hasCar,
           //default: TransportType.Car
        },
    }
});

function hasCar() {
    return JSON.stringify(this.car) !== JSON.stringify({});//this.car; && Object.keys(this.car).length > 0;
}
使用测试代码

var u1 = new UUU({
    email: 'test.user1@email.com'
});

u1.save(function(err) {
    if (err)
        console.log(err);
    else
        console.log('save u1 successfully');
});

var u2 = new UUU({
    email: 'test.user1@email.com',
    car: {carType: 23}
});

u2.save(function(err) {
    if (err)
        console.log(err);
    else
        console.log('save u2 successfully');
});
结果:

{ "_id" : ObjectId("56db9d21d3fb99340bcd113c"), "email" : "test.user1@email.com", "__v" : 0 }
{ "_id" : ObjectId("56db9d21d3fb99340bcd113d"), "email" : "test.user1@email.com", "car" : { "carType" : 23 }, "__v" : 0 }

但是,如果存在
carType
默认值,这里可能有一种解决方法

var UserSchema = new Schema({
    email: {
        type: 'String',
        required: true
    },
    car: { 
        carType: {
           type: 'Number',
           required: hasCar,
           default: 1
        },
    }
});

function hasCar() {
    if (JSON.stringify(this.car) === JSON.stringify({carType: 1})) {
        this.car = {};
    }
    return JSON.stringify(this.car) === JSON.stringify({});
}

UserSchema.pre('save', function(next){
    // if there is only default value of car, just remove this default carType from car 
    if (JSON.stringify(this.car) === JSON.stringify({carType: 1})) {
        delete this.car;
    }
    next();
});
使用上述测试代码,结果如下所示

{ "_id" : ObjectId("56db9f73df8599420b7d258a"), "email" : "test.user1@email.com", "car" : null, "__v" : 0 }
{ "_id" : ObjectId("56db9f73df8599420b7d258b"), "email" : "test.user1@email.com", "car" : { "carType" : 23 }, "__v" : 0 }

谢谢,所需的功能是我真正需要的。