{
    "componentChunkName": "component---src-templates-blog-post-js",
    "path": "/graphql-apollo-node-mongodb-restapi/",
    "result": {"data":{"site":{"siteMetadata":{"title":"CrewCode Solutions"}},"markdownRemark":{"id":"4dc7e8b2-b7fd-5770-a45d-a4cc712e79c2","excerpt":"In this article i will explain you step by step to setup GraphQL API with Apollo Server, Node and MongoDb Step By Step Step 1: Initial project setup and…","html":"<p>In this article i will explain you step by step to setup GraphQL API with Apollo Server, Node and MongoDb Step By Step</p>\n<h4>Step 1: Initial project setup and installing dependencies</h4>\n<p>Run below command to initialize project with default settings</p>\n<pre><code class=\"language-js\">npm init -y\n</code></pre>\n<p>Run below command to install mongoose, graphql and apollo-server</p>\n<pre><code class=\"language-js\">npm install mongoose graphql apollo-server\n</code></pre>\n<p>Run below command to install nodemon as a dev dependencies</p>\n<pre><code class=\"language-js\">npm install --save-dev nodemon\n</code></pre>\n<h4>Step 2: Create GraphQl Schema and Resolvers</h4>\n<p>We will be creating rest api to save, update, delete notes for that we need to define <strong><em>graphql schema which define type of post and get query we will be executing</em></strong> and <strong><em>resolvers which act as controller and we will be writing logic here to interact with our mongodb database</em></strong></p>\n<p><strong><em>Create a folder name graphql under root path of your project</em></strong> under that folder create two js file with the name resolvers.js and schema.js</p>\n<p><strong><em>Update the schema.js file</em></strong> with the following code</p>\n<pre><code class=\"language-js\">const { gql } = require(\"apollo-server\");\n\n//GraphQL Schemas\nmodule.exports = gql`\n  type Note {\n    _id: ID!\n    title: String!\n    content: String!\n    createdAt: String!\n    updatedAt: String!\n  }\n\n  input NoteInputData {\n    title: String!\n    content: String!\n  }\n\n  type Query {\n    getNotes: [Note!]!\n    getNote(id: ID!): Note!\n  }\n\n  input NoteInputData {\n    title: String!\n    content: String!\n  }\n\n  type Mutation {\n    createNote(noteInput: NoteInputData): Note!\n    updateNote(id: ID!, noteInput: NoteInputData): Note!\n    deleteNote(id: ID!): Boolean\n  }\n`;\n</code></pre>\n<p><strong><em>Update the resolvers.js file</em></strong> with the following code</p>\n<pre><code class=\"language-js\">const Note = require(\"../models/note\");\n\nmodule.exports = {\n  Query: {\n    getNote: async (parent, args) => {\n      try {\n        const { id } = args;\n        const note = await Note.findById(id);\n        if (!note) {\n          const error = new Error(\"No note found!\");\n          error.code = 404;\n          throw error;\n        }\n        return note;\n      } catch (error) {\n        throw new Error(error);\n      }\n    },\n    getNotes: async (parent, args) => {\n      try {\n        const notes = await Note.find();\n        return notes;\n      } catch (error) {\n        throw new Error(error);\n      }\n    },\n  },\n\n  Mutation: {\n    createNote: async (parent, args) => {\n      try {\n        const { noteInput } = args;\n        return await Note.create(noteInput);\n      } catch (error) {\n        throw new Error(error);\n      }\n    },\n    updateNote: async (parent, args) => {\n      try {\n        const { id, noteInput } = args;\n        const note = await Note.findById(id);\n        if (!note) {\n          const error = new Error(\"No note found!\");\n          error.code = 404;\n          throw error;\n        }\n        return await Note.findOneAndUpdate(id, noteInput, { new: true });\n      } catch (error) {\n        throw new Error(error);\n      }\n    },\n    deleteNote: async (parent, args) => {\n      try {\n        const { id } = args;\n        const note = await Note.findById(id);\n        if (!note) {\n          const error = new Error(\"No post found!\");\n          error.code = 404;\n          throw error;\n        }\n        await Note.findByIdAndDelete(id);\n        return true;\n      } catch (error) {\n        throw new Error(error);\n      }\n    },\n  },\n};\n</code></pre>\n<h4>Step 3: Create mongoose schema model</h4>\n<p><strong><em>Create a folder name models under root path of your project</em></strong> and create note.js file under that folder</p>\n<p><strong><em>Update note.js file</em></strong> with following code</p>\n<pre><code class=\"language-js\">const mongoose = require(\"mongoose\");\nconst Schema = mongoose.Schema;\n\nconst noteSchema = new Schema(\n  {\n    title: {\n      type: String,\n      required: true,\n    },\n    content: {\n      type: String,\n      required: true,\n    },\n  },\n  { timestamps: true }\n);\n\nmodule.exports = mongoose.model(\"Note\", noteSchema);\n</code></pre>\n<h4>Step 4: Create app.js file under root path of your project</h4>\n<p>File app.js is the main file to start Apollo server and connect to mongodb database</p>\n<p>Update your app.js file with the following code</p>\n<pre><code class=\"language-js\">const { ApolloServer } = require(\"apollo-server\");\nconst graphqlSchema = require(\"./graphql/schema\");\nconst graphqlResolver = require(\"./graphql/resolvers\");\nconst mongoose = require(\"mongoose\");\n\nmongoose\n  .connect(\"mongodb://localhost:27017/notes\", {\n    useNewUrlParser: true,\n    useUnifiedTopology: true,\n  })\n  .then(() => {\n    console.log(\"Connected to database\");\n  })\n  .catch((error) => {\n    throw new Error(error);\n  });\n\nconst server = new ApolloServer({\n  typeDefs: graphqlSchema,\n  resolvers: graphqlResolver,\n});\n\n//Starting apollor server\nserver.listen().then(({ url }) => {\n  console.log(`Server listening at ${url}`);\n});\n</code></pre>\n<h4>Step 5: Run the app and test the api</h4>\n<p><strong><em>Update your package.json file and add start script</em></strong> and update nodemon to start your app.js file which is the main file to start the server</p>\n<pre><code class=\"language-js\">    \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" &#x26;&#x26; exit 1\",\n    \"start\": \"nodemon app.js\"\n  },\n</code></pre>\n<p>Go to your terminal and go to your folder path and run below command to start the apollo server</p>\n<pre><code class=\"language-js\">npm start\n</code></pre>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Graphql-api-with-apollo-server-1.png\" alt=\"typescript-install\"></p>\n<p>Go to <a href=\"http://localhost:4000/graphql\">http://localhost:4000/graphql</a> and start querying your rest api</p>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Graphql-api-with-apollo-server-2.png\" alt=\"typescript-install\"></p>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Graphql-api-with-apollo-server-3.png\" alt=\"typescript-install\"></p>","fields":{"slug":"/graphql-apollo-node-mongodb-restapi/"},"frontmatter":{"title":"Create GraphQl API with Apollo Server, Node and MongoDb","date":"September 22, 2022","description":"In this article i will explain you step by step to setup GraphQL API with Apollo Server, Node and MongoDB","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/GraphQL.jpg"}},"previous":{"fields":{"slug":"/google-authentication-firebase-react-native/"},"frontmatter":{"title":"Google authentication with firebase in react native android application","date":"September 10, 2022","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/google-authentication-reactnative.jpeg"}},"next":{"fields":{"slug":"/how-to-create-firebase-function/"},"frontmatter":{"title":"How to create, deploy and work with firebase function","date":"September 30, 2022","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/firebase-node.jpeg"}}},"pageContext":{"id":"4dc7e8b2-b7fd-5770-a45d-a4cc712e79c2","previousPostId":"82f31d34-4583-5b2a-aa39-370f32173ccb","nextPostId":"b4fc562c-2e59-5977-afbb-8112e8ed3064"}},
    "staticQueryHashes": ["3860684146"]}