我正在使用聚合来加入3个收藏集。但是联接的结果是一个空的array []。 这是我所有3个集合的模型,以及汇总查询。 console.log(timetable)的结果返回[]。我使用引用来引用时间表中具有相应集合的字段。
时间表模型
var TimetableSchema = new mongoose.Schema ({
timeslot: {
required: true,
'type': String,
},
classroom :{
type: mongoose.Schema.Types.ObjectId,
ref: 'Classroom'
},
subject :{
type: mongoose.Schema.Types.ObjectId,
ref: 'Subject'
},
teacher :{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
day :{
type:String,
required: true,
},
year :{
type:String,
required: true,
},
session :{
type:String,
required:true,
}
})
教室模式
var ClassroomSchema = new mongoose.Schema ({
classroom_name: {
type:String,
required:true,
unique: true,
},
classroom_blok:{
type:String,
required:true,
},
classroom_floor: {
type:String,
required:true,
},
});
主题
var SubjectSchema = new mongoose.Schema ({
subject_id: {
required: true,
'type': String,
'default': shortid.generate
},
subject_name: {
type:String,
required:true,
},
subject_darjah:{
type:String,
required:true,
}
});
汇总查询
router.get('/today_absentee/view/:id',function(req,res){
Teacher.findById(req.session.userId).exec(function (error, user){
if (error){
return next(error);
}else
{
Teacher.find({_id:req.params.id }).exec(function(err, teacher){
if(err)
{
return next(err);
}else
{
Timetable.aggregate([
{
// This is doing the same thing as the previous .find()
$match: { teacher:req.params.id}
},
{
$lookup:{
from: "Classroom", // other table name
localField: "classroom", // name of users table field
foreignField: "_id", // name of userinfo table field
as: "classroom" // alias for userinfo table
}
},
{ $unwind:"$classroom" }, // $unwind used for getting data in object or for one record only
{
$lookup:{
from: "Subject", // other table name
localField: "subject", // name of users table field
foreignField: "_id", // name of userinfo table field
as: "subject" // alias for userinfo table
}
},
{ $unwind:"$subject" }, // $unwind used for getting data in object or for one record only
// define some conditions here
{
$match:{
$and:[{teacher:req.params.id}]
}
},
// define which fields are you want to fetch
{
$project:{
subject_name : "$subject.subject_name",
classroom : "$classroom.classroom_name",
}
}
]).exec(function(err, timetable)
{
// The query output is such that `classroom.classroom_name`
// value is unique for each document
if (err) throw err;
console.log(currentYear);
console.log(timetable);
res.render('creator_content/today_absentee_id',{timetable:timetable, user:user, teacher:teacher});
});
}
});
}
});
});
所有3个模型的模型。
答案 0 :(得分:0)
在文件顶部导入 mongoose ,然后在与聚合查询中的任何对象ID字段匹配时使用 mongoose.Types.ObjectId()。 我还使用了 $ addFields 聚合管道来添加2个字段(subject_name,教室),然后在下一个阶段使用 $ project 输出它们。
$2