How to use Mongoose with Apollo Graphql
By: Abhishek Kumar Gupta
Tags: Node Js Tutorial, GraphQL, Mongoose, Apollo Server, Mongodb

Presently use of Graphql Apis in increasing day by day. One day I got the same task at my company for creating api on Apollo Graphql. I went through too many articles but I didn’t got any exact article for using mongoose ORM for connecting Mongodb Atlus with Apollo Graphql application. That’ s why this Idea come into my mind to write a block on “How to use Mongoose with Apollo Graphql”.

Let’s go through step by step.

Create a new folder where you want to keep your code. For example here I have created new folder “apollo-graphql-mongoose " Now run npm init and keep the default package configuration. Now run “ npm install apollo-server graphql mongoose" Now create a new file named “index.js” and paste the following code.

const { ApolloServer, gql } = require('apollo-server'); const resolverss = require("./resolvers") const mutations = require("./mutations"); const mongoose = require("mongoose"); // A schema is a collection of type definitions (hence "typeDefs") // that together define the "shape" of queries that are executed against // your data. mongoose.connect('mongodb://localhost:27017/covertree_life', {useNewUrlParser: true, useUnifiedTopology: true}) .then(()=>console.log('mongoose up')) .catch(error=>console.log(error.message)); mongoose.Promise = global.Promise; const typeDefs = gql` type Book { title: String author: String } type Customer { _id:ID! firstName:String lastName:String address:String unit:String } type Query { books: [Book] customers:[Customer] } type Mutation { createCustomer(firstName:String!, lastName:String!, address:String!, unit:String): Customer! } `; // Resolvers define the technique for fetching the types defined in the // schema. This resolver retrieves books from the "books" array above. const resolvers = { Query: {...resolverss}, Mutation:{...mutations} }; // The ApolloServer constructor requires two parameters: your schema // definition and your set of resolvers. const server = new ApolloServer({ typeDefs, resolvers }); // The `listen` method launches a web server. server.listen().then(({ url }) => { console.log(`🚀 Server ready at ${url}`); });

Now create a new folder named “models” inside root directory. Inside this create new folder Customer.js.

const mongoose = require('mongoose'); const Schema = mongoose.Schema; const customerSchema = new Schema({ _id: mongoose.Schema.Types.ObjectId, firstName: {type:String}, lastName: {type:String}, address: {type:String}, unit:{type:String} }, {timestamps:true}) module.exports = mongoose.model('Customer', customerSchema)

Now create new folder named as “mutations” in the root directory. Inside this create two new files. “customer .js” and “index.js”. Now paste the following inside customer.js.

const Customer = require("../models/Customer"); const mongoose = require("mongoose"); module.exports = { createCustomer: async(_, { firstName, lastName, address, unit }, req) => { // console.log(args); console.log(firstName, lastName, address, unit); try{ let customer = new Customer({ _id: new mongoose.Types.ObjectId, firstName:firstName, lastName:lastName, address:address, unit:unit }); let result = await customer.save(); return result; } catch (error) { throw new Error (error.message); } } }

Paste the following code inside index.js file

const customerMutation = require("./customer"); const rootResolver = { ...customerMutation }; module.exports = rootResolver;

Now create new folder named “resolvers” inside root directory. Now create three new files named “book.js”, “customer.js” and “index.js” inside resolvers.

Now paste the following code inside “book.js”.

const Customer = require("../models/Customer"); const books = [ { title: 'The Awakening', author: 'Kate Chopin', }, { title: 'City of Glass', author: 'Paul Auster', }, ]; module.exports = { books: async () => { // let result = await Customer.insertMany([ // { // name:"Abhishek", // email:"abhishek@yopmail.com" // } // ]) // console.log(result); return books } }

Paste the following code inside “customer.js”.

const Customer = require("../models/Customer"); const mongoose = require("mongoose"); module.exports = { customers: async() => { try{ let result = await Customer.find({}); return result; } catch (error) { throw new Error (error.message); }

}

}

Now paste the following code inside “index.js”

const bookResolver = require("./book"); const customerResolver = require("./customer"); const rootResolver = { ...bookResolver, ...customerResolver }; module.exports = rootResolver;

Now your Apollo graphql api is ready. Now run nodemon and enjoy coding. If you are curious to learn new things please like and subscribe my YouTube channel. Also like my facebook page for new notifications.