简体   繁体   中英

GraphQL and Mongoose: When querying, populate references in subdocuments

This is my schema, and in MongoDB I have separate collections for users, events and movies due to the large number of events and movies:

type Event {
  id: ID!
  title: String!
  description: String!
  creator: User!
}
type Movie {
  id: ID!
  title: String!
  releaseDate: String
}
type MovieStatus {
  movie: Movie
  status: StatusEnum  // WATCHED, PLANNING_TO_WATCH
}
type User {
  id: ID!
  firstName: String!
  createdEvents: [Event!]
  movies: [MovieStatus!]
}

And I want to create the following query:

query {
  user(id: "12345") {
    id
    firstName
    createdEvents{
      id
      title
      description
    }
    movies{
      movie {
        id 
        title 
        releaseDate
      }
      status
    }
  }
}

I have no problem getting the events, by including this in my resolvers:

User: {
    createdEvents: ({ createdEvents }) =>
      Event.find({ _id: { $in: createdEvents } }),
  },

But I can't figure out how to access the movie id, title and release dates.

movies: ({ movies }) => {
  return Promise.all(
    movies.map(async (m) => {
      const movie = m
      movie.movie = await Movie.findById(movie.movie)
      return movie
    })
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM