如何在GraphQLObjectType中定义对象字段?MongoDB+GraphQL+Mongoose用户集合查询
Hey there! Let's tackle your two questions one by one to get your GraphQL + Mongoose setup working smoothly.
1. Defining Fields in a GraphQLObjectType
To define fields in a GraphQLObjectType, you’ll use the constructor from the graphql package, where each field specifies its data type and optionally a resolver function to handle data fetching/transformation.
Here’s a quick breakdown with examples:
- First, import core GraphQL types like
GraphQLString,GraphQLObjectType - Wrap fields in a function to avoid circular dependency issues with nested types
- For each field, declare its
type(built-in or custom) and add aresolvefunction if you need to pull data from a source like MongoDB
Example of a basic nested object type:
const { GraphQLObjectType, GraphQLString } = require('graphql'); const AddressType = new GraphQLObjectType({ name: 'Address', fields: () => ({ street: { type: GraphQLString }, city: { type: GraphQLString }, zipCode: { type: GraphQLString }, }), });
2. Creating a GraphQL User Type for Your Mongoose Schema & Setting Up Queries
Let’s map your existing Mongoose User Schema to a GraphQL type, then add queries to fetch user data from MongoDB.
Step 1: Build the GraphQL User Type
We’ll mirror the nested structure of your Mongoose schema (like the name object with firstName/lastName):
const { GraphQLObjectType, GraphQLString, GraphQLID } = require('graphql'); const User = require('./pathToServer/server/models/user.js'); // Import your Mongoose model // Define the nested Name type first const NameType = new GraphQLObjectType({ name: 'Name', fields: () => ({ firstName: { type: GraphQLString }, lastName: { type: GraphQLString }, }), }); // Now define the main User type const UserType = new GraphQLObjectType({ name: 'User', fields: () => ({ id: { type: GraphQLID }, // Automatically maps to Mongoose's _id field name: { type: NameType }, email: { type: GraphQLString }, // Important: Never expose the password field in your GraphQL type for security! }), });
Step 2: Add Query Resolvers
Create a root query type to fetch single or multiple users. Resolvers are where you’ll interact with your Mongoose model to pull data from MongoDB:
const { GraphQLObjectType, GraphQLList, GraphQLID } = require('graphql'); const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { // Fetch a single user by ID user: { type: UserType, args: { id: { type: GraphQLID } }, resolve(parent, args) { // Use Mongoose's findById method to fetch the user return User.findById(args.id); }, }, // Fetch all users users: { type: new GraphQLList(UserType), resolve(parent, args) { return User.find({}); // Empty object fetches all documents }, }, }, });
Step 3: Test Your Queries
Once your schema is set up, you can test these queries in tools like GraphQL Playground:
Fetch a single user:
query { user(id: "your-mongodb-user-id") { id name { firstName lastName } email } }
Fetch all users:
query { users { id name { firstName } email } }
Key Tips:
- Security: Keep sensitive fields like
passwordout of your GraphQL type—only use them for authentication logic behind the scenes. - Resolver Flexibility: You can use any Mongoose method in resolvers (e.g.,
findOne,findById) to filter or modify data before returning it. - Type Alignment: Ensure your GraphQL field types match your Mongoose schema types (e.g.,
GraphQLStringfor MongooseString,GraphQLIDfor MongoDB’s_id).
内容的提问来源于stack exchange,提问作者alfaneo

