繁体   English   中英

mongodb 中的嵌套文档引用与 mongoose

[英]Nested document referencing in mongodb with mongoose

我正在尝试使用带有 rest api 的 mern 堆栈为我的投资组合构建看板。 我在查询具有深度嵌套对象的模型时遇到问题。 我的想法是在项目中引用列表,在列表中引用任务,在任务中引用用户,并将项目作为贡献者。 我的问题是通过使用 mongoose 或 MongoDB 填充项目 model 来获取任务的信息(标题等)。 我应该如何处理这个? 甚至可以用 MongoDB 做吗? 我看到很多人使用 sql 数据库这样做。 四个 model 架构如下:

const projectSchema = new Schema({
  title: { type: String, required: true, max: 32, trim: true },
  lists: [{ type: Schema.Types.ObjectId, ref: 'List' }],
  contributors: [{ type: Schema.Types.ObjectId, ref: 'User' }],
});

const listSchema = new Schema({
  title: { type: String, required: true, max: 32, trim: true },
  tasks: [{ type: Schema.Types.ObjectId, ref: 'Task' }],
});

const taskSchema = new Schema({
  title: { type: String, required: true, max: 38, trim: true },
  text: { type: String, max: 255, trim: true },
  assignee: { type: Schema.Types.ObjectId, ref: 'User' },
});

const userSchema = new Schema(
    Name: { type: String, required: true, trim: true },
    projects: [{ type: Schema.Types.ObjectId, ref: 'Project' }],
    tasks: [{ type: Schema.Types.ObjectId, ref: 'Task' }],
);

我遇到的问题是在列表中显示任务。 当我用项目调用填充列表时,我得到了任务的 ObjectId,但想得到任务标题,这似乎是不可能通过再次应用 .populate 调用来实现的。 我有以下 api 控制器/路由:

router.get('/:projectId', async (req, res) => {
  try {
    const project = await Project.findOne({
      _id: req.params.projectId,
    }).populate('lists', 'title tasks');

    res.json(project);
  } catch (error) {
    if (error) {
      console.error(error.message);
      res.status(500).send('Server Error');
    }
  }
});

我将如何获取任务标题以及稍后引用项目列表中所有任务的用户名?

所以我找到了解决方案。 不确定这是否是解决此问题的最有效方法。 如果有人可以提供更好的解决方案,请在此处发布。

我发现 mongoose 文档很好地解释了如何填充多个级别。

https://mongoosejs.com/docs/populate.html#deep-populate

现在答案的解决方案如下

router.get('/:projectId', async (req, res) => {
  try {
    const project = await Project.findOne({
      _id: req.params.projectId,
    }).populate({ path: 'lists', populate: { path: 'tasks' } });

    res.json(project);
  } catch (error) {
    if (error) {
      console.error(error.message);
      res.status(500).send('Server Error');
    }
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM