[英]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個集合(不包括“用戶帳戶”集合)
我可以通過簡單的“查找”請求從“部分”和“項目”中獲取數據。 例如:
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.