数组中 ObjectId 上的$lookup不起作用



我有与这个问题中相同的情况:$lookup on ObjectId';s在一个数组中(我不能对这个问题发表评论,因为我没有足够的声誉…很抱歉重复…(-但是这个查询对我不起作用,最后我得到了一个空数组。

我想得到一份带有职位字段的公司列表,但职位字段总是空的关于以下代码。(我得到了company字段,使用$undup,甚至连company字段都不会返回(。

我做错了什么?

猫鼬版本:5.7.14mongodb版本: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集合。

最新更新