<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Joshua Pozos</title>
    <description>The latest articles on DEV Community by Joshua Pozos (@joshuapozos).</description>
    <link>https://dev.to/joshuapozos</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F459915%2Fe869f24f-a335-49ea-b811-c4392ba120cf.jpeg</url>
      <title>DEV Community: Joshua Pozos</title>
      <link>https://dev.to/joshuapozos</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/joshuapozos"/>
    <language>en</language>
    <item>
      <title>GraphQL Server Using NEXT.js and MongoDB Atlas</title>
      <dc:creator>Joshua Pozos</dc:creator>
      <pubDate>Mon, 02 Aug 2021 23:41:17 +0000</pubDate>
      <link>https://dev.to/joshuapozos/graphql-server-using-next-js-and-mongodb-atlas-93i</link>
      <guid>https://dev.to/joshuapozos/graphql-server-using-next-js-and-mongodb-atlas-93i</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;First, sorry if something is not well written, I am still learning English&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Add the following dependencies in your project
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add apollo-server-micro@2.25.1 mongoose graphql
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;blockquote&gt;
&lt;p&gt;I used this version of apollo-server-micro because the new version 3 sends you to a sandbox that in my opinion is uncomfortable.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the root of your project create a folder with the name you prefer, in this case I use "db". Inside create two more folders, one called "config" and the other "models"&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir db &amp;amp;&amp;amp; cd db &amp;amp;&amp;amp; mkdir config &amp;amp;&amp;amp; mkdir models
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk3f2fvj66a3gb3qejnj6.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk3f2fvj66a3gb3qejnj6.jpeg" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Config
&lt;/h3&gt;

&lt;p&gt;Inside the config folder create an index.js file and add "moongose". For the MongoDb uri it is good practice to add it inside an .env file and bring it with proccess.env.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require('mongoose')

const MongoDb = process.env.MONGODB_URI

const connectDb = async () =&amp;gt; {
  try {
    await mongoose.connect(MongoDb, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useFindAndModify: false,
      useCreateIndex: true,
    })
    console.log('db success connect')
  } catch (err) {
    console.log('error connecting to database')
    console.log(err)
    process.exit(1)
  }
}

module.exports = connectDb
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Models
&lt;/h3&gt;

&lt;p&gt;Now we are going to create an example model, in this case the product model. So inside the "models" folder I create a file called product.js and add moongose and what I need for the model.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import mongoose from 'mongoose'

const { Schema } = mongoose

mongoose.Promise = global.Promise

const ProductsSchema = new Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  productionCapacity: {
    type: Number,
    required: true,
    trim: true,
  },
  price: {
    type: Number,
    required: true,
    trim: true,
  },
  description: {
    type: String,
    trim: true,
  },
  createAt: {
    type: Date,
    defalut: Date.now(),
  },
})

ProductsSchema.index({ name: 'text' })

module.exports =
  mongoose.models.Product || mongoose.model('Product', ProductsSchema)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Schema and resolvers
&lt;/h3&gt;

&lt;p&gt;I'll leave the code here as an example because your project can be totally different.&lt;/p&gt;
&lt;h4&gt;
  
  
  Schema
&lt;/h4&gt;

&lt;p&gt;For the schema we will import &lt;code&gt;gql&lt;/code&gt; from &lt;code&gt;apollo-server-micro&lt;/code&gt; and create a constant called "typeDefs" in which we will use &lt;code&gt;gql&lt;/code&gt; and inside we will define our types, inputs, queries and mutations&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { gql } from 'apollo-server-micro'

const typeDefs = gql`
  # Products
  type Product {
    id: ID
    name: String
    productionCapacity: Int
    price: Float
    description: String
  }

  input ProductInput {
    name: String!
    productionCapacity: Int!
    price: Float!
    description: String
  }

  type Query {
    getProducts: [Product]
    getProduct(id: ID!): Product
  }

  type Mutation {
    #Products
    newProduct(input: ProductInput): Product
    updateProduct(id: ID!, input: ProductInput): Product
    deleteProduct(id: ID!): String
  }
`

module.exports = typeDefs

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  Resolvers
&lt;/h4&gt;

&lt;p&gt;I will leave the code that I use, but remember that your project can be very different. We bring the models, in this case I bring my "product" model to be able to use it within the queries or mutations that I define.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Product = require('./models/product')

const resolvers = {
  Query: {
    // products
    getProducts: async () =&amp;gt; {
      try {
        const products = await Product.find({})

        return products
      } catch (err) {
        console.log(err)
      }
    },
    getProduct: async (_, { id }) =&amp;gt; {
      const product = await Product.findById(id)

      if (!product) {
        throw new Error('Product not found')
      }

      return product
    },
  },

  Mutation: {
    // products
    newProduct: async (_, { input }) =&amp;gt; {
      try {
        const product = new Product(input)

        const result = await product.save()

        return result
      } catch (err) {
        console.log(err)
      }
    },
    updateProduct: async (_, { id, input }) =&amp;gt; {
      let product = await Product.findById(id)

      if (!product) {
        throw new Error('Product not found')
      }

      product = await Product.findOneAndUpdate({ _id: id }, input, {
        new: true,
      })

      return product
    },
    deleteProduct: async (_, { id }) =&amp;gt; {
      const product = await Product.findById(id)

      if (!product) {
        throw new Error('Producto no encontrado')
      }

      await Product.findOneAndDelete({ _id: id })

      return 'Producto eliminado'
    },
  },
}

module.exports = resolvers

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Creating the endpoint
&lt;/h3&gt;

&lt;p&gt;First we create a graphql.js file (it can be called whatever) inside /pages/api.&lt;br&gt;
In the graphql.js file we are going to import &lt;code&gt;ApolloServer&lt;/code&gt; and &lt;code&gt;makeExecutableSchema&lt;/code&gt; from &lt;code&gt;apollo-server-micro&lt;/code&gt; and &lt;code&gt;typeDefs&lt;/code&gt;, &lt;code&gt;resolvers&lt;/code&gt; and &lt;code&gt;connectDb&lt;/code&gt; from their corresponding files. Then we run the &lt;code&gt;connectDb()&lt;/code&gt; function and create a schema with &lt;code&gt;makeExecutableSchema&lt;/code&gt; which will have the &lt;code&gt;typeDefs&lt;/code&gt; and the &lt;code&gt;resolvers&lt;/code&gt;.&lt;br&gt;
And at the end we export the Apollo Server passing it our schema variable and defining the path that must match the name of the file that we put in /pages/api.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { ApolloServer, makeExecutableSchema } from 'apollo-server-micro'
import typeDefs from '../../db/schema'
import resolvers from '../../db/resolvers'
import connectDb from '../../db/config'

connectDb()

export const schema = makeExecutableSchema({
  typeDefs,
  resolvers
})

export const config = {
  api: {
    bodyParser: false,
  },
}

export default new ApolloServer({ schema }).createHandler({
  path: '/api/graphql',
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Your project should have been more or less like this&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7vnhwkd6eojebi4ld149.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7vnhwkd6eojebi4ld149.jpeg" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now run the project and go to the url of your api with graphql&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl3jccklkxbrobcf3dc46.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl3jccklkxbrobcf3dc46.jpeg" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I leave the package.json for you to check the version of the dependencies used in this post.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "graphql-nextjs",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "apollo-server-micro": "2.25.1",
    "graphql": "^15.5.1",
    "mongoose": "^5.13.5",
    "next": "11.0.1",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {
    "eslint": "7.32.0",
    "eslint-config-next": "11.0.1"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Repo
&lt;/h2&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/JoshuaPozos" rel="noopener noreferrer"&gt;
        JoshuaPozos
      &lt;/a&gt; / &lt;a href="https://github.com/JoshuaPozos/graphql-nextjs" rel="noopener noreferrer"&gt;
        graphql-nextjs
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;div class="markdown-heading"&gt;
&lt;h1 class="heading-element"&gt;GraphQL Server Using NEXT.js and MongoDB Atlas&lt;/h1&gt;

&lt;/div&gt;

&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Setup&lt;/h2&gt;

&lt;/div&gt;

&lt;div class="snippet-clipboard-content notranslate position-relative overflow-auto"&gt;&lt;pre class="notranslate"&gt;&lt;code&gt;yarn install
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Create ur own &lt;code&gt;MONGODB_URI&lt;/code&gt; into .env file (.env.development or .env.local) and add ur mongodb uri.&lt;/p&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Ready&lt;/h2&gt;

&lt;/div&gt;

&lt;p&gt;Modify all u need to ur project&lt;/p&gt;

&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Development mode&lt;/h2&gt;

&lt;/div&gt;

&lt;div class="snippet-clipboard-content notranslate position-relative overflow-auto"&gt;&lt;pre class="notranslate"&gt;&lt;code&gt;yarn dev
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;

  &lt;/div&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/JoshuaPozos/graphql-nextjs" rel="noopener noreferrer"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;



</description>
      <category>nextjs</category>
      <category>graphql</category>
      <category>mongodb</category>
      <category>react</category>
    </item>
  </channel>
</rss>
