猫鼬中的GraphQL关系

时间:2018-09-22 14:14:46

标签: javascript mongoose graphql

我有以下GraphQL模式

type User {
  id: String!
  name: String
  username: String!
}

type Conversation {
  id: String!
  participants: [User]
}

type Query {
  user(_id: String!): User
  conversation(_id: String!): Conversation
}

我的对话解析器如下:

conversation: async (parent, args) => {
  let conversation = await Conversation.findById(args._id);
  conversation.id = conversation._id.toString();
  return conversation;
}

participants字段将保存用户ObjectId的数组。我需要在解析器中执行什么操作,以便可以在conversation调用中获取用户数据。

例如这样的呼叫

query test($id:String!){
  conversation(_id:$id){
    id,
    participants {
      id,
      username
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您可能在对象模型中使用了引用,因此,为了获取参与者数据,您应该使用mongoose populate

这将为您工作:

conversation: async (parent, args) => {
  let conversation = await Conversation.findById(args._id).populate('participants');
  conversation.id = conversation._id.toString();
  return conversation;
}
相关问题