DEV Community

Samuel Kauffmann
Samuel Kauffmann

Posted on

Apollo mongoose plugin

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.

Alt Text

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()],
});
Enter fullscreen mode Exit fullscreen mode

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:

  1. Add indexes to optimize search
  2. Use a Dataloader to group called in one.
  3. Cache query result (for example in Redis) to serve it later
  4. Use persisted GraphQL queries

Top comments (0)