Moongoose嵌套对象

时间:2017-09-27 17:26:11

标签: node.js mongodb mongoose mongoose-schema

我需要创建一个用户架构,其中用户可以是3个可接受的选项之一: admin,teacher,student 。我想把它全部放在一个Schema中,就像这样:

var userSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
username: String,
password: String,
role: {
     type: String, 
     enum: ['admin', 'teacher', 'student'], // only accepts these values
     default: 'student'
},
admin: {
    // some fields related to admin
},
teacher: {
    degree: String,
},
student: {
    indexNumber: String,
}
});

我可以在角色中嵌套 admin 和其他人,如下所示:

role: {
     type: String, 
     enum: ['admin', 'teacher', 'student'], // dozvoljava samo ove vrednosti
     default: 'student',
     admin: {
        // some fields related to admin
    }, ...
}

或者这是完全错误的方法,我应该为管理员,教师和学生制作3个以上的模式,并将它们连接到此userSchema?

1 个答案:

答案 0 :(得分:0)

您可以使用鉴别器

将用户架构继承为三种不同的子类型

http://mongoosejs.com/docs/discriminators.html

来自mongoose文档的示例

var options = {discriminatorKey: 'kind'};

var eventSchema = new mongoose.Schema({time: Date}, options);
var Event = mongoose.model('Event', eventSchema);

// ClickedLinkEvent is a special type of Event that has
// a URL.
var ClickedLinkEvent = Event.discriminator('ClickedLink',
  new mongoose.Schema({url: String}, options));