首页 > 解决方案 > 数组中 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
      // },
      ]);


标签: mongodbmongooseaggregatelookup

解决方案


Mongoose 根据约定创建 MongoDB 集合。Position由于模型名称被翻译成复数形式positions,因此您的查询应如下所示:

{ 
    $lookup: { 
        from: 'positions',
        localField: '_id',
        foreignField: 'companyId',
        as: 'positions' 
    }  
}

第一个参数是您的模型所针对的集合的单数名称。** Mongoose 会自动查找您的型号名称的复数、小写版本。** 因此,对于上面的示例,模型 Tank 用于数据库中的 tank 集合。


推荐阅读