我有一个美丽的多级模型,使得在进行不需要嵌套FOR编程逻辑的查询时,会使我复杂化。
var Schema = new mongoose.Schema({
name: String,
date_deadline:Date,
tasks:[{
type:mongoose.Schema.Types.ObjectId,
ref: 'task'
}],
status: {
type:Number,
default: 0
},
},
{ timestamps: true }
)
任务模型如下:
var Schema = new mongoose.Schema({
name: {
type: String,
required: [true, 'ERROR_REQUIRED'],
trim:true,
},
deadline:Date,
status:{
type:String
},
minutes:{
type: Number,
min: 0
},
asign:[
{
type:mongoose.Schema.Types.ObjectId,
ref: 'task_asign'
}
],
},
{ timestamps: true }
)
TaskAsign是这样的:
var Schema = new mongoose.Schema({
task_type: {
type:mongoose.Schema.Types.ObjectId,
ref: 'task_type'
},
collab: {
type:mongoose.Schema.Types.ObjectId,
ref: 'contributor'
},
historic:[
{
type:mongoose.Schema.Types.ObjectId,
ref: 'task_asign_historic'
}
]
},
{ timestamps: true }
)
最后一个模型是TaskAsignHistoric:
var Schema = new mongoose.Schema({
collab: {
type:mongoose.Schema.Types.ObjectId,
ref: 'contributor'
},
minutes:{
type: Number,
default: 0
}
},
{ timestamps: true }
)
我需要从贡献者ID中提取;状态为“完成”的任务需要花费几分钟。它们出现在历史记录数组中的TaskAsign(以及此模型的分钟数),以及列出任务的项目。
我已经在forEachs中尝试了awaits,但是它不是异步上下文,因此无法运行。
let tAsign = await mTaskAsign.find().or([{ historic: ObjectId(id) }, { collab: ObjectId(id) }])
let historic = await mTaskAsignHistoric.find({ collab: ObjectId(id) })
let asign = [];
tAsign.forEach(iAsign=>{
let tasks = await mTasks.find({ asign:{ $in: iAsign} }) || [];
let item = {
'task':task,
'project':null
}
if (task){
let proj = await mProj.find({ tasks:{ $in: task} }) || [];
item['project'] = proj;
}
但是我没有一个很好的结果,代码也不是值得骄傲的。
有人可以帮助我使用Agregate或某种Moongoose查询来解决问题,而无需诉诸所有元素吗? 像这样:
let projst = await mProj.find({'tasks.asign.collab':ObjectId(id)}).populate("tasks");