【问题标题】:How to join two table with aggregate for Deno and MongoDB?如何将两个表与 Deno 和 MongoDB 的聚合连接起来?
【发布时间】:2023-03-25 02:05:01
【问题描述】:

现在,我正在学习 Deno,并尝试使用 Deno 和 MongoDb 进行简单的应用程序。到目前为止,一切都很顺利。但是今天,我想加入两个具有聚合功能的表。我的示例代码在这里:

const result = await articles.aggregate([
    {
      $lookup: {
        from: "authors",
        localField: "oid",
        foreignField: "author_id",
        as: "author",
      },
    },
    {
      $unwind: "$author",
    },
  ]);
  req.send(result);

我想要一个像下面这样的输出。但是目前,虽然我的数据库中只有 3 篇文章,但它会将这些作者与所有作者进行匹配,并带来总共 6 条记录。

My output

我认为问题是由以下原因引起的。但我不确定。

// My output id format
"_id": {
      "$oid": "5ed7abfc00f94b9c0048ba5e"
},

// what will be written in the localfield field in this section
$lookup: {
        from: "authors",
        localField: "oid",
        foreignField: "author_id",
        as: "author",
},

我在等你的帮助。

【问题讨论】:

  • oid改为_idoid只是ObjectId的缩写。
  • 我这样做了,但返回了一个空数组
  • 根据你给它的名字,你似乎也需要在localFieldforeignField之间切换。
  • 我试过那个方法。同样,空数组返回。我希望错误的 _id 值是一个对象,它包含 $oid 变量。
  • 我能想到的唯一其他原因是author_id 不是oid 而是string

标签: mongodb join aggregate deno


【解决方案1】:

我还没有找到解决这个问题的正确方法,但我通过以下方式解决了它。

  var result = await articles.find();
  for(var i=0; i<result.length; i++){
    result[i].author = await authors.findOne({ _id: { $oid: result[i].author_id } });
  }
  req.send(result);

我的问题是由于 ObjectId。 Deno 尚不支持此功能。我相信他们很快就会解决问题。

【讨论】:

  • 你找到更好的选择了吗?
猜你喜欢
  • 2015-02-20
  • 2021-09-28
  • 2021-04-11
  • 1970-01-01
  • 2020-05-12
  • 2020-07-22
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多