Connecting GraphQL to MongoDB
GraphQL does not care which database stores your data. MongoDB is a natural fit for many Node.js applications because JavaScript objects can be mapped relatively naturally to MongoDB documents.
A useful architecture is:
GraphQL Resolver
↓
Application Service
↓
Repository
↓
Mongoose Model
↓
MongoDB
For example, a resolver should preferably call a service:
const resolvers = {
Query: {
user: (_, { id }, context) => {
return context.userService.getById(id);
}
}
};
The service can call a repository:
const getById = (id) => userRepository.findById(id);
The repository can use Mongoose:
const findById = (id) => UserModel.findById(id).lean();
This separation prevents GraphQL resolver code from becoming tightly coupled to Mongoose.
It also makes it easier to replace the persistence layer or reuse the same business logic from a REST API, background worker, or command-line tool.
GraphQL to MongoDB Architecture
Key Takeaways
- GraphQL should not be tightly coupled to MongoDB.
- Services and repositories create useful separation between API and persistence.
- Mongoose can be used as the MongoDB data-access layer.
- The same business services can potentially support multiple API entry points.
Knowledge Check
What is a major benefit of placing a repository between a GraphQL service and Mongoose?