使用mongoose mongo加入两个不同的集合(按ID)

时间:2019-02-23 05:41:45

标签: mongodb mongoose

如何添加到两个收藏夹?我已经尝试并查看了一些现有查询,但找不到解决方案。

我有这两个模型

作者

const Author = mongoose.model(
  "Author",
  new mongoose.Schema({
    name: {
      type: String,
      required: true
    },
    slack_user: {
      type: String,
      required: false,
      default: null
    }
  })
);

短语

我用短语指代作者

const Phrase = mongoose.model(
  "Phrase",
  new mongoose.Schema({
    phrase: {
      type: String,
      required: true
    },
    author: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Author",
      required: true
    }
  })
);

预期结果 我想要得到的结果是拥有作者的信息以及属于他的短语列表。

{
"_id": "5c704e67f8eb6f699cdc0f8b",
"name": "pepe",
"slack_user": "ocococ",
"__v": 0,
"author_prhases": ["String one", "String two", ...]
}

我尝试过的是:

Author.aggregate([
    {
      $lookup: {
        localField: "_id",
        from: "Phrase",
        foreignField: "author",
        as: "author_prhases"
      }
    }
  ])



{
  "_id": "5c704e67f8eb6f699cdc0f8b",
  "name": "pepe",
  "slack_user": "ocococ",
  "__v": 0,
  "author_prhases": [] //empty

携带相关信息的方式是什么?

1 个答案:

答案 0 :(得分:0)

我找到了答案,我正在使用猫鼬,并且在创建模型时使用大写字母,当生成集合时,它是使用小写字母生成的,则聚合的FROM引用必须使用小写字母。为此,如果不确定mongo生成的集合名称,请查看它的名称。

Author.aggregate([
    {
      $lookup: {
        localField: "_id",
        from: "phrases", //the collection name, (bad)before i had Phrase as the model
        foreignField: "author",
        as: "author_prhases"
      }
    }
  ])
相关问题