javascript - 嵌套引用的猫鼬过滤器
问题描述
我有 3 个猫鼬模式员工、团队和项目。员工引用了团队,团队引用了项目。是否可以通过项目 ID 获取所有员工?我不想更改架构或使用带有填充的团队模型。
const employeeSchema = mongoose.Schema({
email: { type: String, required: true, unique: true },
team: { type: mongoose.Schema.Types.ObjectId, ref: "Team" },
});
const teamSchema = mongoose.Schema({
name: { type: String, required: true },
employees: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
project: { type: mongoose.Schema.Types.ObjectId, ref: "Project" },
});
下面的代码抛出转换错误,id 是一个有效的项目 id。
router.get("/:id/employees", checkAuth, (req, res, next) => {
const id = req.params.id;
console.log(id);
Employee.find({ team:{project:id}}).then((employees) => {
console.log(employees);
});
});
解决方案
是的,可以让所有员工使用项目 ID。但不使用单个查询,所以你必须像这样修改你的函数
const id = mongoose.Types.ObjectId(req.params.id);
Team.findOne({ project: id }, { _id: 1 }, function (err, docs) {
// Get the Team which match with project ID
Employee.find({ team: docs._id }, function (err, docs1) {
//Get all employee belongs to that team and project
console.log(docs1);
});
});
推荐阅读
- angular - 通过 webpack 代理从帖子中发送标头
- ios - Xamarin IoS 12 更新:WKWebView 自定义渲染器问题
- android - 有没有办法增加 Android 中的 BLE 广告频率?
- c++ - 计算选择排序中的交换次数和比较次数
- azure - 使用 GraphQL 连接 CosmosDB?
- imacros - 提取和搜索列
- mysql - 是否可以在一个命令中写入一个表?
- java - ManyToOne 关系,父级可以更新/删除/添加子级,但父级列表在子级保存/删除时也会更新,没有级联
- python - Python 字符串列表到 1 个字符串,用逗号和引号 (, & ") 分隔
- python-2.7 - pybind11 embed 留下未清理的进程