Mongoose使用另一个Model对象填充数组字段

时间:2017-02-21 01:38:44

标签: node.js mongodb mongoose

我真的很困惑如何处理这个问题。我想使用特定的 StudyGroup 模型填充我的 User 模型的studyGroups数组。我通过路由器(用户cuid: req.params.cuid和studyGroup的guid: req.params.guid)获取特定用户和studyGroup。

以下是我的代码:

用户

const userSchema = new Schema({
  cuid: { type: 'String', required: true },
  firstName: { type: 'String', required: true },
  lastName: { type: 'String', required: true },
  studentId: { type: 'Number', required: true },
  password: { type: 'String', required: true },
  email: { type: 'String', required: true },
  dateAdded: { type: 'Date', default: Date.now, required: true },
  lastLogin: { type: 'Date', default: null, required: false },
  studyGroups: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "studyGroup"
      }
    ]
});

StudyGroup

const studyGroupSchema = new Schema({
  guid: { type: 'String', required: true },
  groupName: { type: 'String', required: true },
  course: { type: 'String', required: true },
  teacher: { type: 'String', required: true },
  description: { type: 'String', required: true },
  dateAdded: { type: 'Date', default: Date.now, required: true },
});

路线

router.route('/:cuid/studyGroups/:guid').post(UserController.addUserStudyGroups);

这是所有行动发生的地方。首先我找到了用户,现在我想将整个studyGroup模型对象添加到数组中。所以我的想法是使用guid: req.params.guid查询 studyGroup ,但不知道这是否正确。

控制器

export function addUserStudyGroups(req, res) {
  User.findOne({ cuid: req.params.cuid }).populate('studyGroups').exec((err, studyGroups) => {
    if (err) {
      return res.status(500).send(err);
    }
    study
    return res.json({ studyGroups });
  });
}

1 个答案:

答案 0 :(得分:1)

您现在可以使用$lookup

在Mongo 3.2中执行此操作

$lookup需要四个参数

from:指定同一数据库中的集合以执行连接。 from集合无法分片。

localField:指定输入到$ lookup阶段的文档中的字段。 $ lookup通过from集合的文档在localField上执行与foreignField的相等匹配。

foreignField:指定from集合中文档的字段。

as:指定要添加到输入文档的新数组字段的名称。新数组字段包含来自集合的匹配文档。

db.User.aggregate(
  {$unwind: "$bars"},
  {$lookup: {
    from:"studyGroups",
    localField: "studyGroups",
    foreignField: "_id",
    as: "studyGroupList"

   }}
)
相关问题