【发布时间】: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');
}
}
});
对于引用项目的列表中的所有任务,我将如何获取任务标题和用户名?
【问题讨论】: