【问题标题】:$lookup on ObjectId's in an array does not work数组中 ObjectId 的 $lookup 不起作用
【发布时间】: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


【解决方案1】:

Mongoose 根据约定创建 MongoDB 集合。 Position 型号名称将 translated 变为复数形式 positions 因此您的查询应如下所示:

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

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

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 2018-01-10
    • 2021-08-25
    相关资源
    最近更新 更多