我有以下用户架构(其中合并了不同用户类型的所有不同属性):
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}]
}
"普通"架构(所有用户类型的共同点):
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
}
角色="客户":
address: [{type: Object, required: true}]
角色=" DeliveryMan":
deliverySchedule: [{type: String, required: true}]
organization: [{ type: mongoose.Schema.Types.ObjectId, required: true,
ref: 'Organization' }],
角色="卖方":
organization: [{ type: mongoose.Schema.Types.ObjectId, required: true,
ref: 'Organization' }],
我想在" common"中添加(并在可能的情况下请求)一些字段。基于用户角色的模式。但是,我想将它们存储在同一个集合中。
如何向我的models/Users.js
添加方法,以便根据" user.role"
答案 0 :(得分:1)
为每个与角色相关的字段选择require
validation。
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"
}
}
};