chalo
chalo

Reputation: 1059

Join two different collections (by id) with mongoose mongo

How can I add to two collections? I have tried and reviewed several of the existing queries but I can not find a solution.

I have these two models

Author

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

Phrase

In phrase I am making a reference to Author

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

Expected result The result I want to get to is to have the author's information along with a list of Phrases that belong to him.

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

What I have tried has been:

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



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

What is the way to bring the related information?

Upvotes: 1

Views: 3299

Answers (1)

chalo
chalo

Reputation: 1059

I found the answer, I'm using mongoose, and when creating the model use capital letters, when the collection is generated it is generated with lowercase letters, then the FROM reference of the aggregation must be in lowercase. To do this look at the name of the collection that mongo generated if you are not sure of what it is called.

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

Upvotes: 2

Related Questions