DEV Community

Karthikeyan
Karthikeyan

Posted on

simple way to fetch data from mongoDB using graphQl and Apollo (React JS)

Today i am going to show you how to write simple fetch data from mongoDB using Apollographql

npm i apollo-server-express express graphql lodash mongoose nodemon 
Enter fullscreen mode Exit fullscreen mode

after install these

import { ApolloServer } from 'apollo-server-express';
import { ApolloServerPluginDrainHttpServer } from 'apollo-server-core';
import express from 'express';
import http from 'http';
import {typeDefs} from './utils/typeDefs.js'
import {resolvers} from './utils/resolvers.js'
import mongoose from 'mongoose'

async function startApolloServer(typeDefs, resolvers) {
  const app = express();
  const httpServer = http.createServer(app);
  // Same ApolloServer initialization as before, plus the drain plugin.
  const server = new ApolloServer({
    typeDefs,
    resolvers,
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
  });

  await server.start();
  server.applyMiddleware({
    app,
    path: '/',
  });
  app.use((req,res)=>{
    res.send('Hello frontend')
  })
      //mongoDB connection
  await mongoose.connect('mongodb://localhost:27017/demo')
  console.log('mongoose connected')
  // Modified server startup
  await new Promise(resolve => httpServer.listen({ port: 4000 }, resolve));
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
}

startApolloServer(typeDefs,resolvers);  // start the server 
Enter fullscreen mode Exit fullscreen mode

A schema is a JSON object that defines the the structure and contents of your data

mongoDB models

// const mongoose = require('mongoose');
import mongoose from 'mongoose'

const schema = new mongoose.Schema({
    message:{
        type:String,
        required:true
    },
},{collection:'test'})

export const test = mongoose.model('test',schema) //collection name and schema name

Enter fullscreen mode Exit fullscreen mode

A GraphQL schema is a description of the data clients can request from a GraphQL API. It also defines the queries and mutation functions that the client can use to read and write data from the GraphQL server

import { gql } from "apollo-server-express";

export const typeDefs = gql`
type Query {
    getmessages : [Message!]!
    getlimitmessage(limit : Int) : [Logs!]! // if you want limited no of messages just create a schema like this
}

type Message {
 message: MessageInput! 
}

input MessageInput {
    message: String,
}

type Mutation {
    createMessage(message: MessageInput!): Message
}

Enter fullscreen mode Exit fullscreen mode

resolvers : A resolver is a function that's responsible for populating the data for a single field in your schema

import {test} from './models.js'
import _ from 'lodash'
export const resolvers = {
    Query : {
        getmessages: async ()=>{
          return await test.find() //here i am using lodash 
           //function to get all the messages from the database 
        },
        getlimitmessage: async (limit)=>{
            return await _.takeRight(test,limit) //get limited number of messages from the database
        }
    },
    Mutation : {
        createMessage: (_,args,) => {
            let addMessage = new test(args.message)
            return addMessage.save()
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)