繁体   English   中英

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

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

我需要在以下json字符串中填充“任务”。

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

它当前包含3个集合(不包括“用户帐户”集合)

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

我可以通过简单的“查找”请求从“部分”和“项目”中获取数据。 例如:

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到常量userProjectSections ,像这样

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

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

干杯!

暂无
暂无

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

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