2016-03-05 48 views
1

我有模型,其中汽車屬性是可選的,但汽車嵌套文檔中有一些屬性,如果用戶有汽車,如cartype : {required: true},但是汽車被定義時應該要求。Mongoose中的動態驗證

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

回答

1

如果沒有用於carType沒有default值,我們可以定義一個函數hasCar到的carTyperequired如下

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: '[email protected]' 
}); 

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

var u2 = new UUU({ 
    email: '[email protected]', 
    car: {carType: 23} 
}); 

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

結果:

{ "_id" : ObjectId("56db9d21d3fb99340bcd113c"), "email" : "[email protected]", "__v" : 0 } 
{ "_id" : ObjectId("56db9d21d3fb99340bcd113d"), "email" : "[email protected]", "car" : { "carType" : 23 }, "__v" : 0 } 

但是,如果是carTypedefault值,這裏也許有解決辦法

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" : "[email protected]", "car" : null, "__v" : 0 } 
{ "_id" : ObjectId("56db9f73df8599420b7d258b"), "email" : "[email protected]", "car" : { "carType" : 23 }, "__v" : 0 } 
+0

謝謝,需要的功能是我真正需要。 – VahagnNikoghosian