Intereting Posts

基于属性的dynamicMongoose模式

我有以下用户架构(其中不同用户types的所有不同属性被合并):

var UserSchema = new mongoose.Schema({ status: String, firstName: String, lastName: String, address: Object, email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true}, organization: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Organization' }], phone: {type: Number, unique: true, required: true, required: [true, "can't be blank"]}, role: String, hash: String, salt: String, deliverySchedule: [{type: String, required: true}] } 

“通用”模式(所有用户types共享的):

 var UserSchema = new mongoose.Schema({ status: String, firstName: String, lastName: String, email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true}, phone: {type: Number, unique: true, required: true, required: [true, "can't be blank"]}, role: String, hash: String, salt: String } 

angular色=“客户”:

  address: [{type: Object, required: true}] 

angular色=“送货员”:

  deliverySchedule: [{type: String, required: true}] organization: [{ type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Organization' }], 

Role =“卖家”:

  organization: [{ type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Organization' }], 

我想添加(和REQUIRE如果可能的话)一些字段的基础上的“普通”模式的angular色。 但是,我想将它们存储在同一个集合中。

如何添加一个方法到我的models/Users.js基于“user.role”添加属性到模式

Solutions Collecting From Web of "基于属性的dynamicMongoose模式"

使require validation对每个angular色相关字段都是可选的。

 var UserSchema = new mongoose.Schema({ status: String, firstName: String, lastName: String, email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true}, phone: {type: Number, unique: true, required: true, required: [true, "can't be blank"]}, role: {type: String, enum: ['Customer', 'DeliveryMan', 'Seller'], required: true}, address: {type: [Object], required: isRequired("address")}, deliverySchedule: {type: [String], required: isRequired("deliverySchedule")}, organization: { type: [mongoose.Schema.Types.ObjectId], ref: 'Organization', required: isRequired("organization")}, hash: String, salt: String }); function isRequired(field){ return function(){ if(field == "address"){ return this.role === "Customer" } else if(field == "deliverySchedule"){ return this.role === "DeliveryMan" } else if(field == "organization"){ return this.role === "Seller" || this.role === "DeliveryMan" } } };