如何从 mongodb 中的子集合中获取数据?

How can I get data from a child collection in mongodb?

我需要在下面的 json 字符串中填充 'tasks'。

{
    "sectionname": "Section1",
    "tasks": [],
    "_id": "5d46e5c4d2e87911d8d4d42c",
    "projectid": "5d46d42333aecb0b6aa3f2ca",
    "userid": "5d46b54635bb9e05b9d33528",
    "time": "2019-08-04T14:03:48.953Z",
    "__v": 0
},

它目前包含 3 个集合(不包括用户帐户集合)

  1. 项目
  2. 部分
  3. 任务

我通过一个简单的 Find 请求从 Section 和 Project 获取数据。例如:

userProjectSections.find({userid: req.user, projectid: req.params.id})

然后我决定添加 .populate('tasks'),但它并没有改变任何东西。任务仍然是空的 [ ].

这是完整的模型。

const userProjects = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    time : { type : Date, default: Date.now },
    complete : { type : Boolean, default: false },
    userid: {type: String, ref: 'user'},
    projectname: {type: String, default: 'New Project'}
});

module.exports = mongoose.model('Projects', userProjects);

const userProjectSections = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    time : { type : Date, default: Date.now },
    complete : { type : Boolean, default: false },
    userid: {type: String, ref: 'user'},
    projectid: {type: String, ref: 'Projects'},
    sectionname: {type: String, default: 'New Section'},
    tasks: [{ type: Schema.ObjectId, ref: 'SectionTasks' }]
});

module.exports = mongoose.model('ProjectSection', userProjectSections);

const userSectionTasks = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    time : { type : Date, default: Date.now },
    complete : { type : Boolean, default: false },
    userid: {type: String, ref: 'user'},
    projectid: {type: String, ref: 'Projects'},
    sectionid: {type: String, ref: 'ProjectSection'},
    task: {type: String, default: 'New task'}
});

module.exports = mongoose.model('SectionTasks', userSectionTasks);

理论上,我可以从我的 React frontend 编写另一个 API 调用,但我更愿意从单个请求中获取数据并包含任务。

结束了 const userSectionTasks 并添加了一个额外的数组 Tasks 到 const userProjectSections 中,就像这样

tasks: [{
        _id: mongoose.Schema.Types.ObjectId,
        task: String,
        postedBy: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'user'
        }
    }]

现在我可以简单地使用 $addToSet 向该部分添加新任务。

干杯!