How to join two collections in mongoose

前端 未结 2 1114
孤独总比滥情好
孤独总比滥情好 2021-02-04 11:45

I have two Schema defined as below:

var WorksnapsTimeEntry = BaseSchema.extend({
 student: {
     type: Schema.ObjectId,
     ref: \'Student\'
 },
 timeEntries:          


        
2条回答
  •  梦谈多话
    2021-02-04 12:09

    As of version 3.2, you can use $lookup in aggregation pipeline to perform left outer join.

    Student.aggregate([{
        $lookup: {
            from: "worksnapsTimeEntries", // collection name in db
            localField: "_id",
            foreignField: "student",
            as: "worksnapsTimeEntries"
        }
    }]).exec(function(err, students) {
        // students contain WorksnapsTimeEntries
    });
    

提交回复
热议问题