DEV Community

Danish Siraj
Danish Siraj

Posted on • Updated on

Creating a GraphQL Server from just Mongoose Models

Introduction

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js and is one of the most common libraries that NodeJs developers are acquainted with. Mongoose has been used widely for REST applications, with the coming of GraphQL, which is a query language for APIs to get exactly what you need, a simple interface to bridge both seemed to be missing.

To fill this gap and automatically generate a GraphQL Server from just mongoose models and provide basic CRUD operations for all models with support for deep nested populations, I created this library mongoose-graphql-server.

Getting Started

To get started with this library and generate CRUD with GraphQL on just mongoose models.

Note: Assuming MongoDB is installed locally or the connection string needs to be changed accordingly, to test with a free cloud MongDB database checkout MongoDB Atlas

Make a directory for the project.

In that directory initiate a new NodeJs project with npm or yarn

With npm

$ npm init -y
Enter fullscreen mode Exit fullscreen mode

With yarn

$ yarn init -y
Enter fullscreen mode Exit fullscreen mode

Install the required dependencies

$ npm install mongoose mongoose-graphql-server --save
Enter fullscreen mode Exit fullscreen mode

Or

$ yarn add mongoose mongoose-graphql-server
Enter fullscreen mode Exit fullscreen mode

Create a file index.js for the server code

const mongoose = require('mongoose');
const {
  generateSchema,
  createGraphQLServer,
} = require('mongoose-graphql-server');
const PORT = process.env.port || 3000;

mongoose.connect('mongodb://localhost/test');
const db = mongoose.connection;

const init = async () => {
  // Register models

  const userModel = mongoose.model('user', {name: String, age: Number});
  const catModel = mongoose.model('cat', {name: String});
  // Build the schema

  const schema = generateSchema(mongoose);

  // Create the graphQL server

  const app = await createGraphQLServer(schema);

  // Start the server

  app.listen(PORT, () => {
    console.log(
      `🚀🚀🚀 The server is running at http://localhost:${PORT}/`,
      `The GraphQL explorer is running at http://localhost:${PORT}/graphql`
    );
  });
};

db.once('open', init);

Enter fullscreen mode Exit fullscreen mode

Start the server with

$ node index.js
Enter fullscreen mode Exit fullscreen mode

If there are no errors, head over to GraphQL endpoint to start exploring using the GraphQL explorer.

This screen should be visible on successful server start
Image description

This was just a basic introduction more documentation and examples can be found on mongoose-graphql-server or the GitHub repository

Any type of feedback is highly appreciated as this is my first npm package and since Hacktoberfest is upon us contributions to this project are also welcomed.

Top comments (0)