gpt4 book ai didi

node.js - 基于属性的动态 Mongoose Schema

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:52 25 4
gpt4 key购买 nike

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

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' }],

我想根据用户的角色向“通用”模式添加(如果可能的话需要)一些字段。但是,我想将它们存储在同一个集合中。

如何向我的 models/Users.js 添加方法,以根据“user.role”向架构添加属性

最佳答案

使需要 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"
}
}
};

关于node.js - 基于属性的动态 Mongoose Schema,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com