【问题标题】:GraphQL and Mongoose: When querying, populate references in subdocumentsGraphQL 和 Mongoose:查询时,在子文档中填充引用
【发布时间】:2021-03-31 15:41:10
【问题描述】:

这是我的架构,在 MongoDB 中,由于事件和电影的数量很大,我有单独的用户、事件和电影集合:

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!]
}

我想创建以下查询:

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

通过将其包含在我的解析器中,我可以毫无问题地获取事件:

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

但我不知道如何访问电影 ID、标题和发行日期。

【问题讨论】:

  • 你必须先解析User.movies - MovieStatus 的数组
  • @xadm - 对此还是很陌生。你能解释一下吗?
  • “电影”中存储了什么? (电影 ID + 状态)列表?获取 id 列表,查找电影,然后使用源对将结果与状态连接...返回对象数组 { status, movie {id, title, release} }

标签: node.js mongodb mongoose graphql


【解决方案1】:
movies: ({ movies }) => {
  return Promise.all(
    movies.map(async (m) => {
      const movie = m
      movie.movie = await Movie.findById(movie.movie)
      return movie
    })
  )
}

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 2016-06-18
    • 2018-08-16
    • 2017-01-27
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 2020-12-18
    • 2015-08-08
    相关资源
    最近更新 更多