是否可以在 mongoose 中填充一个包含其他信息的字段?

Is it possible to populate a field in mongoose which has other information on it too?

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

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

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

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

将您的架构更改为:

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