首页 > 解决方案 > Node、GraphQL + MongoDB:查询多对多关系

问题描述

我正在使用 Express、GraphQL 和 MongoDB 构建服务器。我不确定我的 Mongo 数据建模或 GraphQl Schema 设置可能需要指导。对于这个例子,我有一个用户模型和一个目标模型。用户可以有多个目标,我计划将目标 ID 存储在用户模型上。用户查询正在运行,但目标返回 null。

const UserSchema = new Schema({
  firstName: { type: String, required: true },
  ...
  goals: [{ type: Schema.Types.ObjectId, ref: "Goal" }]
});

const GoalSchema = new Schema({
  goal: { type: String, required: true },
  users: [{ type: Schema.Types.ObjectId, ref: "User" }]
});

下面是 GraphQL 架构:

const UserType = new GraphQLObjectType({
  name: "User",
  fields: () => ({
    id: { type: GraphQLID },
    firstName: { type: GraphQLString },
    ...
    goals: {
      type: new GraphQLList(GoalType),
      resolve(parent, args) {
        return Goal.find({ id: parent.goals });
      },
    },

  }),
});

解决此问题的最佳方法是什么?

标签: mongodbexpressmongoosegraphqlmongoose-schema

解决方案


推荐阅读