【发布时间】:2020-06-02 21:08:47
【问题描述】:
我的情况与这个问题相同:$lookup on ObjectId's in an array(我无法评论这个问题,因为我没有足够的声誉......抱歉重复......) - 但是 该查询对我不起作用,最后我得到一个空数组。
我想获取包含职位字段的公司列表,但职位字段始终为空 在下面的代码上。 (我得到了公司字段,并且使用了 $unwind - 甚至公司字段也没有返回)。
我做错了什么?
猫鼬版本: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
// },
]);
【问题讨论】:
-
你试过了吗:
from: 'positions'? -
no.. 现在试过了,它有效!你知道为什么它会有所作为吗?
标签: mongodb mongoose aggregate lookup