【问题标题】:Need to get list of records grouped by foreign key in Mongoose需要在 Mongoose 中获取按外键分组的记录列表
【发布时间】:2020-01-02 18:20:38
【问题描述】:

我有 2 个表interestTypes 和interests 表,兴趣记录存储了interestTypeId 引用。

现在我需要兴趣类型列表及其兴趣。

const interestSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      trim: true,
      minlength: 3,
      maxlength: 50,
      required: true
    },
    interestTypes: [
      {
        interestTypeId: {
          type: mongoose.SchemaTypes.ObjectId,
          ref: 'interestType'
        }
      }
    ]
  },
  {
    timestamps: true
  }
)

const interestTypeSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      trim: true,
      minlength: 3,
      maxlength: 50,
      required: true
    }
  },
  {
    timestamps: true
  }
)

我知道这可以通过查找聚合来完成,但我搞砸了。这段代码是用兴趣模型写的

interestSchema.statics.getTypes = function() {
    return new Promise((resolve, reject) => {

    this.aggregate([
      {
        "$lookup":
          {
            "from": "interestTypes",
            "localField": "interestType",
            "as": "interestTypes",
            "foreignField": "_id",
          }
      },
      {
        "$group": 
          {
            "_id": "$_id",
            "interestTypes": { "$push": "$interestTypes" }
          }
        }
    ],
      function(err, result) {
        if (err) return reject(err)        
        resolve(result)
      }
    )
}

无法得到想要的结果

我希望这个方法返回的是这样的

[
{
    id: interestTypeIdRef1,
    name: interestType1
    interests: [
    {
        id: interestIdRef1,
        name: interestType1
    },
    {
        id: interestIdRef2,
        name: interestType2
    },
    {
        id: interestIdRef3,
        name: interestType3
    }
    ]
},
{
    id: interestTypeIdRef2,
    name: interestType1
    interests: [
    {
        id: interestIdRef2,
        name: interestType1
    },
    {
        id: interestIdRef3,
        name: interestType2
    },
    {
        id: interestIdRef4,
        name: interestType3
    }
    ]
}
]

【问题讨论】:

    标签: mongodb mongoose aggregate lookup


    【解决方案1】:

    从interestTypeSchema 开始聚合以获得所需的输出。

    InterestSchema.statics.getTypes = function () {
    return new Promise((resolve, reject) => {
    
        interestType.aggregate([
            {
                $lookup: {
                    from: 'interestSchema',
                    localField: '_id',
                    foreignField: 'interestTypeId',
                    as: 'interests'
                }
            },
            {
                $project: {
                    name:1,
                    interests:1,
                }
            }
        ],
            function (err, result) {
                if (err) return reject(err)
                resolve(result)
            }
        )
    }
    

    【讨论】:

    • 它仍然没有给我兴趣数组。 [{ id:interestTypeIdRef1,名称:interestType1 },{ id:interestTypeIdRef2,名称:interestType1 }]
    • 谢谢@vishal 但现在它给出了空列表 [{ id: interestTypeIdRef1, name: interestType1,interests: [] },{ id: interestTypeIdRef2, name: interestType1,interests: [] }]
    【解决方案2】:

    您可以使用下面的链接来检查查询。 这是在聚合中进行查找的查询

    已创建示例数据库

    db={
      "interestTypes": [
        {
          "typeId": 1,
          "type": "type1"
        },
        {
          "typeId": 2,
          "type": "type2"
        }
      ],
      "interests": [
        {
          "_id": 1,
          "interestName": "interest1",
          "interestTypeId": 1
        },
        {
          "_id": 2,
          "interestName": "interest2",
          "interestTypeId": 1
        },
        {
          "_id": 3,
          "interestName": "interest3",
          "interestTypeId": 2
        },
        {
          "_id": 4,
          "interestName": "interest4",
          "interestTypeId": 2
        },
        {
          "_id": 5,
          "interestName": "interest5",
          "interestTypeId": 1
        }
      ]
    }
    

    示例答案

    db.interestTypes.aggregate([
      {
        $lookup: {
          from: "interests",
          localField: "typeId",
          foreignField: "interestTypeId",
          as: "interesetTypesWithInterest"
        }
      },
      {
        $project: {
          type: 1,
          interestTypeId: "$typeId",
          interests: "$interesetTypesWithInterest"
        }
      }
    ])
    

    使用此链接进行验证 https://mongoplayground.net/p/3f5AzKQMamw 既然您熟悉将 mongodb 代码转换为 Mongoose,它将对您有所帮助。

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • 同意你的建议。
    • @MihaiChelaru 这不应该意味着你不赞成答案。我已经编辑了我的答案。
    • 我不是对您的答案投反对票的人。我只是在审查队列中遇到它并采取了适当的措施。不要以为我投了反对票,因为自动生成的评论来自我。
    • 不用担心,@MihaiChelaru 感谢您的建议。这将有助于我将来发布更多解释性答案。
    猜你喜欢
    • 2014-03-23
    • 1970-01-01
    • 2011-02-03
    • 2016-04-21
    • 2021-04-24
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    相关资源
    最近更新 更多