mongodb - 数组中 ObjectId 的 $lookup 不起作用
问题描述
我有与这个问题相同的情况:$lookup on ObjectId's in an array(我无法评论这个问题,因为我没有足够的声誉......抱歉重复......) - 但查询没有' t 为我工作,最后我得到一个空数组。
我想获得一个包含职位字段的公司列表,但在以下代码中,职位字段始终为空。(我得到了公司字段,并且使用了 $unwind - 甚至公司字段也没有返回)。
我究竟做错了什么?
mongoose 版本:5.7.14 mongodb 版本:4.2.3
我还尝试了很多聚合和填充的组合,但都没有成功。
const schema = new Schema(
{
email: {
type: String,
required: true,
unique: true
},
name: {
type: String,
required: true,
unique: true
},
positionsIds: [{
type: Schema.Types.ObjectId,
ref: 'Position',
require: false
}
);
module.exports = mongoose.model('Company', schema);
-----------------------------
const schema = new Schema(
{
title: {
type: String,
required: true
},
requirements: [{
years: { type: Number, required: false },
skill: { type: String, required: false },
}],
companyId: {
type: Schema.Types.ObjectId,
ref: 'Company',
required: true
},
}
);
module.exports = mongoose.model('Position', schema );
---------------------------
let companies = await Company.aggregate([
{
$lookup:
{
from: 'Position',
localField: '_id',
foreignField: 'companyId',
as: 'positions'
}
},
// {
// $unwind: '$positions' // - mess the query even more and return an empty array
// },
]);
解决方案
Mongoose 根据约定创建 MongoDB 集合。Position
由于模型名称被翻译成复数形式positions
,因此您的查询应如下所示:
{
$lookup: {
from: 'positions',
localField: '_id',
foreignField: 'companyId',
as: 'positions'
}
}
第一个参数是您的模型所针对的集合的单数名称。** Mongoose 会自动查找您的型号名称的复数、小写版本。** 因此,对于上面的示例,模型 Tank 用于数据库中的 tank 集合。
推荐阅读
- azure-devops - Azure DevOps:如何查找变量组链接到的所有发布计划
- javascript - 使用 jQuery 和 AJAX 正确格式化表格
- sml - 包含所有数字的最小子列表
- php - 将在数据库中搜索的结果链接到另一个页面
- javascript - vue-test-utils:无法覆盖属性 $route,这通常是由于插件将该属性添加为只读值
- angular - 运行应用程序之前的 Angular Universal 错误
- .net - 如何使用 Nancy.testing 测试这个模块
- django - 如何正确编写需要处理复杂对象的api(检索、创建、更新方法)
- node.js - NodeJS Express 和 ReactJS 的 CORS 错误
- django - 函数“prefetch_related”的“*lookups”参数的品种