【问题标题】:Mongoose populate an array field with another Model objectMongoose 用另一个 Model 对象填充数组字段
【发布时间】:2017-02-21 19:56:54
【问题描述】:

我真的很困惑如何解决这个问题。我想用特定的 StudyGroup 模型填充我的 User 模型的 studyGroups 数组。我通过路由器获取特定的用户和 studyGroup(cuid: req.params.cuid 为用户,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"
      }
    ]
});

研究组

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您现在可以在 Mongo 3.2 中使用 $lookup 进行此操作

    $lookup 接受四个参数

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

    localField:指定从文档输入到 $lookup 阶段的字段。 $lookup 对 from 集合的文档中的 localField 到 foreignField 执行相等匹配。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-09
      • 2019-08-26
      • 1970-01-01
      • 2023-04-01
      • 2012-01-22
      • 2022-01-24
      • 2016-01-19
      • 1970-01-01
      相关资源
      最近更新 更多