gpt4 book ai didi

node.js - 如何在 Mongoose 中加入两个集合

转载 作者:搜寻专家 更新时间:2023-10-31 22:16:44 25 4
gpt4 key购买 nike

我有两个 Schema 定义如下:

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);
});

有人知道我如何实现这样的目标吗?

最佳答案

从 3.2 版开始,您可以使用 $lookup在聚合管道中执行左外连接。

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

关于node.js - 如何在 Mongoose 中加入两个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36805784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com