MongoDB stores data as flexible documents. GraphQL lets you ask for exactly the data you want. Using them together helps you get data easily and quickly.
MongoDB with GraphQL
type Query {
getItems: [Item]
}
type Item {
id: ID!
name: String
description: String
}
type Mutation {
addItem(name: String!, description: String): Item
}
# Resolver example in JavaScript
const resolvers = {
Query: {
getItems: async () => {
const items = await mongoCollection.find().toArray();
return items.map(item => ({
id: item._id.toString(),
name: item.name,
description: item.description
}));
}
},
Mutation: {
addItem: async (_, { name, description }) => {
const result = await mongoCollection.insertOne({ name, description });
return {
id: result.insertedId.toString(),
name,
description
};
}
}
};GraphQL schema defines what data you can ask for.
Resolvers connect GraphQL queries to MongoDB operations.
query {
getItems {
id
name
}
}query {
getItems {
id
description
}
}mutation {
addItem(name: "Book", description: "A nice book") {
id
name
}
}This program sets up a GraphQL server connected to MongoDB. It defines a query to get all items and a mutation to add a new item. It converts MongoDB's _id to string for GraphQL.
# GraphQL schema definition const { ApolloServer, gql } = require('apollo-server'); const { MongoClient, ObjectId } = require('mongodb'); const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri); const typeDefs = gql` type Item { id: ID! name: String description: String } type Query { getItems: [Item] } type Mutation { addItem(name: String!, description: String): Item } `; async function startServer() { await client.connect(); const db = client.db('testdb'); const itemsCollection = db.collection('items'); const resolvers = { Query: { getItems: async () => { const items = await itemsCollection.find().toArray(); return items.map(item => ({ id: item._id.toString(), name: item.name, description: item.description })); } }, Mutation: { addItem: async (_, { name, description }) => { const result = await itemsCollection.insertOne({ name, description }); return { id: result.insertedId.toString(), name, description }; } } }; const server = new ApolloServer({ typeDefs, resolvers }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); }); } startServer();
GraphQL queries let you ask for only the data you need, reducing data transfer.
Resolvers must convert MongoDB ObjectId to string for GraphQL ID type.
Use async/await to handle MongoDB calls inside resolvers.
MongoDB stores flexible documents; GraphQL queries them precisely.
Define GraphQL schema and resolvers to connect to MongoDB.
Use queries to fetch data and mutations to change data in MongoDB.
Practice
Solution
Step 1: Understand GraphQL's role
GraphQL allows clients to request exactly the data they want, no more, no less.Step 2: Connect to MongoDB data
MongoDB stores flexible documents, and GraphQL queries these documents precisely.Final Answer:
To query only the specific data fields needed from MongoDB -> Option DQuick Check:
GraphQL queries = precise data retrieval [OK]
- Thinking GraphQL replaces MongoDB
- Confusing document storage with tables
- Assuming GraphQL handles backups
Solution
Step 1: Identify GraphQL query syntax
GraphQL queries start with the keywordqueryfollowed by the selection set.Step 2: Check the options
query { users { id name email } } correctly usesquery { users { id name email } }to fetch user fields.Final Answer:
query { users { id name email } } -> Option AQuick Check:
GraphQL query syntax = query + selection set [OK]
- Using mutation instead of query for fetching data
- Omitting braces or keywords
- Writing invalid syntax like 'fetch users from MongoDB'
query { user(id: "123") { name age } }And MongoDB has a user document { _id: "123", name: "Alice", age: 30, city: "NY" }, what will be the query result?
Solution
Step 1: Understand the query fields
The query requests onlynameandagefields for user with id "123".Step 2: Match MongoDB document fields
The document has those fields: name "Alice" and age 30, so those are returned.Final Answer:
{ "data": { "user": { "name": "Alice", "age": 30 } } } -> Option AQuick Check:
Requested fields returned exactly [OK]
- Expecting all document fields returned
- Confusing id with _id field
- Assuming error when user exists
mutation { addUser(name: "Bob", age: "25") { id name } }But you get an error: "Field 'addUser' argument 'age' of type 'Int!' was provided invalid value." What is the likely cause?
Solution
Step 1: Analyze the error message
The error says the 'age' argument type is 'Int!' but the value is invalid.Step 2: Analyze the query literal
The query provides age: "25" as a string literal, but the schema expects an integer literal for Int!, causing the invalid value error.Final Answer:
The age argument was provided as a string, not an integer -> Option CQuick Check:
Type mismatch in argument causes invalid value error [OK]
- Using query instead of mutation for data change
- Ignoring schema argument types
- Assuming numeric values are always valid
updateUser(id: ID!, city: String!): UserWhich resolver code snippet correctly updates the city field in MongoDB?
Solution
Step 1: Identify correct MongoDB update method
findByIdAndUpdateupdates a document by its _id and returns the updated document.Step 2: Check options for update and return
return UserModel.findByIdAndUpdate(id, { city }, { new: true }); usesfindByIdAndUpdatewith{ new: true }to return updated user, matching schema.Final Answer:
return UserModel.findByIdAndUpdate(id, { city }, { new: true }); -> Option BQuick Check:
Use findByIdAndUpdate to update and return new doc [OK]
- Using updateOne without returning updated document
- Deleting instead of updating
- Inserting new document instead of updating existing
Ready to prove it?
Pass the test and this pattern moves unknown
