我有兩個模式,定義如下:如何加入兩個集合的貓鼬
var WorksnapsTimeEntry = BaseSchema.extend({
student: {
type: Schema.ObjectId,
ref: 'Student'
},
timeEntries: {
type: Object
}
});
var StudentSchema = BaseSchema.extend({
firstName: {
type: String,
trim: true,
default: ''
// validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: ''
// validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
type: String,
trim: true
},
municipality: {
type: String
}
});
而且我想環路直通每個學生,並顯示它的時間條目。到目前爲止,我有這樣的代碼顯然是不正確的,因爲我仍然不知道如何加入WorksnapTimeEntry模式表。
Student.find({ status: 'student' })
.populate('student')
.exec(function (err, students) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
_.forEach(students, function (student) {
// show student with his time entries....
});
res.json(students);
});
任何人都知道我該如何做到這一點?
你這樣做是錯誤的。你想''將'WorksnapTimeEntry'的'student'路徑作爲一個源文件'.populate()'。如果你期望它反過來,那麼你要麼在每個'Student'中包含引用作爲一個「數組」,要麼手動查詢和組合,查找'WorksnapTimeEntry'中的「student」字段。 '.populate()'方法只能用對象中的「已存儲」引用。 –
@BlakesSeven我這樣做的事情是,我想先把所有的學生展示在桌面上,然後顯示每個人的時間條目,我不能顯示timeEntries,因爲他們是桌上的數百萬人......我正在嘗試類似這增加了學生模式,但仍然沒有工作:timeEntries:[{type:Schema.Types.ObjectId,ref:'WorksnapsTimeEntry'}], 然後.populate('學生')將像.populate 'timeEntries'),你能告訴我爲什麼這不起作用嗎? –
不,它會是WorksnapsTimeEntry.find()。populate(「students」).exec({..})'因爲'「students」'是該模型中的「路徑」,而「路徑」就是你作爲參數提供給'.populate()'。如果你想要一個不同的格式,那麼你需要重新處理結果。或者正如我已經說過的,您需要創建對「Student」模型文檔中的每個「WorksnapTimeEntry」的引用。這就是'.populate()'的作用。你目前的想法是相反的。 –