【问题标题】:Moongoose Nested Objects猫鼬嵌套对象
【发布时间】:2017-09-28 01:32:45
【问题描述】:

我需要创建一个用户架构,其中用户可以是 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 中吗,如下所示:

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

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

【问题讨论】:

  • 第一种方法有什么问题?我认为这是一个很好的方法。
  • 没有问题,只是我认为它没有遵循良好的做法,例如将字段“admin、teacher、student”与字段“firstName...”放在同一“row”中。另外,例如。如果用户是学生,他的字段对于管理员和老师来说都是 NULL。不确定这是否是好方法,因为学生仍然拥有这些领域?

标签: node.js mongodb mongoose mongoose-schema


【解决方案1】:

您可以使用鉴别器将用户架构继承为三种不同的子类型

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

来自猫鼬文档的示例

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));

【讨论】:

    猜你喜欢
    • 2014-07-26
    • 2014-07-28
    • 2017-01-28
    • 2019-10-12
    • 2014-02-10
    • 2014-07-13
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多