【问题标题】:Nested document referencing in mongodb with mongoose使用 mongoose 在 mongodb 中嵌套文档引用
【发布时间】:2020-10-04 22:38:33
【问题描述】:

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

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

对于引用项目的列表中的所有任务,我将如何获取任务标题和用户名?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

    我发现 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');
        }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2012-10-17
      • 2020-09-03
      • 2017-04-01
      • 2021-07-20
      • 2011-11-10
      • 2014-08-05
      • 2021-05-06
      • 1970-01-01
      • 2021-03-26
      相关资源
      最近更新 更多