Apollo mongoose plugin
Samuel Kauffmann
Posted on April 30, 2021
Let me introduce my new library apollo-mongoose-plugin
.
It's a plugin to add mongoose query information on the Apollo GraphQL response extensions node.
Why you need this plugin?
The purpose of the apollo-mongoose-plugin
is to help you to identify your redundant, long, or un-batched MongoDB queries.
Thanks to GraphQL it's really easy to create a field resolver to load linked data on-demand.
But working on small pieces of data can make us lose the big picture and lead to performance issues.
With this plugin, you will be able to keep a look on global performance and the execution plan of your Mongo queries.
How it works?
The library is composed of 2 plugins. Once to collect query information from Mongoose and the second one to add collected queries on the Apollo GraphQL response.
Usage
Install the plugin with npm install apollo-mongoose-plugin
, then register the mongoCollectorPlugin
to Mongoose and ApolloMongoosePlugin
on the ApolloServer
.
import {
ApolloMongoosePlugin,
mongoCollectorPlugin,
} from 'apollo-mongoose-plugin';
import { ApolloServer } from 'apollo-server';
import mongoose from 'mongoose';
// first: register mongoose query collector plugin
// 🔔 Make sure you are registering the mongoose plugin
// before you are creating mongoose models
mongoose.plugin(mongoCollectorPlugin);
// then: register apollo plugin
const server = new ApolloServer({
// ...schema, dataSources
plugins: [new ApolloMongoosePlugin()],
});
How can I handle performance issues?
I must admit that I am not an expert on this subject but through my experience, I have used at least these few tips:
- Add indexes to optimize search
- Use a
Dataloader
to group called in one. - Cache query result (for example in Redis) to serve it later
- Use persisted GraphQL queries
Posted on April 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.