DEV Community

Mehak Saini
Mehak Saini

Posted on

3 2

#5 Adding MongoDB to react-express-graphql project Part 2

Refer here for Part 1

While using graphql in express, we add the schema and resolvers to set the graphql middleware. Here, we'll be adding a new user to mongo for which we've already created a schema file

./models/user.js

const mongoose=require('mongoose')

const userSchema= new mongoose.Schema({
    email:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    }
})

module.exports=mongoose.model("user",userSchema)
Enter fullscreen mode Exit fullscreen mode

Import the user schema to your server

const User=require("./models/user")
Enter fullscreen mode Exit fullscreen mode

Since, we are performing one of the CRUD operations, let's add the addUser mutation in our code.

type RootMutation{
                addUser(userInput:UserInput!):User!
            }
Enter fullscreen mode Exit fullscreen mode

Let's go ahead and create the User types and User input

            type User{
                _id:ID!,
                email:String!,
                password:String!
            }
            input UserInput{
                email:String!,
                password:String!
            }
Enter fullscreen mode Exit fullscreen mode

As we call the addUser mutation, a corresponding resolver is required to perform the subsequent task of adding the user to database. rootValue denotes the resolver functions.

rootValue: {
      addUser:async (args)=>{
        try{
            const user=new User({
                email:args.userInput.email,
                password:args.userInput.password
            })
            const result=await user.save()
            console.log("result:"+result)
            return{
                ...result._doc
            }
        }
        catch(err){
            console.log(err)
        }
      }
    }
Enter fullscreen mode Exit fullscreen mode

Since we are returning a user on every new user creation, we need to create a new object and set the newly created user's properties to it. We are using async await to cater to asynchronous calls.
In the end, we need to save the user to the db, hence we call user.save()
Let's test it in our playground
graphQL playground
Check your database and you'll see the new user entry
image
Let's add the user query and corresponding resolver and check the result

type RootQuery{
                user(id:ID!):User!
            }
Enter fullscreen mode Exit fullscreen mode
user: async(args) => {
        try{
            const user=await User.findOne({_id:args.id})
            return{
                ...user._doc
            }
        }
        catch(err){
            throw err
        }
      }
Enter fullscreen mode Exit fullscreen mode

graphQL playground

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay