GraphQL Type relationship / Mongoose Schema / populate()

Viewed 604

Having an issue with returning territories related to their Company when running query for retrieving all Companies. When a company is created, a territory is not set. Territories are created separately.

The connections/relations are "territories" within Company and "parentCompany" within Territory. When running getAllTerritories the "parentCompany" is populated correctly (I believe this is due to the fact that you choose the parentCompany upon creation of Territory.

So I guess my question is, What is the best way to populate the territories array on Company when running the getAllCompanies query?

Types:

type Company {
  _id: ID
  state: String!
  name: String
  territories: [Territory]
  createdAt: String
  updatedAt: String
  createdBy: User!
}

type Territory {
  _id: ID
  name: String
  parentCompany: Company!
  issues: [Issue]
  prodAdmins: [ProdAdmin]
  masterAgents: [MasterAgent]
  createdAt: String
  updatedAt: String
  createdBy: User!
}

Query:getAllCompanies: [Company]

getAllCompanies: async (_, args, { Company, Territory }) => {         
      const companies = await Company.find({})
        .sort({ createdAt: 'desc' })
        .populate({
          path: 'territories',
          model: 'Territory',
        })
        .populate({
          path: 'createdBy',
          model: 'User',
        });    
      return companies;
    },

On Company schema:

territories: {
  type: [mongoose.Schema.Types.ObjectId],
  ref: 'Territory',
},
0 Answers
Related