【问题标题】:Is it possible to populate a field in mongoose which has other information on it too?是否可以在 mongoose 中填充包含其他信息的字段?
【发布时间】:2018-03-09 04:38:57
【问题描述】:

这是我的架构的相关部分:

var classroomSchema = mongoose.Schema({
    students: [{
        _id: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        rate: {
            type: Number,
            default: 200,
        },
        referrals: [mongoose.Schema.Types.ObjectId],
    }],
)};

这里的 rate 和 Referres 是学生的属性,在该教室的上下文中有效,不能从学生模型中填充。

有什么方法可以定义我的架构,以便我可以保留这些字段(评分和推荐)并使用填充链接其他字段,例如学生的姓名、年龄等?

【问题讨论】:

标签: node.js mongodb mongoose mongoose-schema mongoose-populate


【解决方案1】:

将您的架构更改为:

var classroomSchema = mongoose.Schema({
    students: [{
        rate: { type: Number, default: 200 },

        user: { ref: 'User', type: Schema.Types.ObjectId },
        referrals: [mongoose.Schema.Types.ObjectId],
    }],
});

用法:

classroom
  .findOne(...)
  .populate('user')
  .exec((err, classroom) => {
    let student0 = classroom.students[0];
    // student0.rate
    // student0.user.name
  });

【讨论】:

  • 有没有更好的办法?在学生数组中保存一个应该是用户数组的用户字段对我来说似乎不自然。
  • user 字段只是对User 的引用。如果可以将用户添加到多个教室,这是最自然的方式。
猜你喜欢
  • 1970-01-01
  • 2020-04-21
  • 1970-01-01
  • 2013-03-23
  • 2012-01-22
  • 2016-02-20
  • 2017-06-17
  • 2018-03-04
  • 2017-05-21
相关资源
最近更新 更多