DEV Community

Mehak Saini
Mehak Saini

Posted on

#3 Adding MongoDB to react-express-graphql project

Setting up Mongo Account

Sign up with Mongo DB Account and click on Create a New Cluster. You may select any free-tier cluster. Note that if you already have a cluster running for a project, you may need to create a new one as only one cluster is free per project. Once you're done creating a new cluster, initiliazing one may take few minutes, meanwhile you can set up Database access and Network settings.MongoDB settings
Click on Add New Database User. Enter the credentials and click on add user. image
Now click on Network access and add IP Address there.
image

Adding Mongoose in express

Now Go back to your express code and import the mongoose npm package using

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

Let's import mongoose by adding

const mongoose = require("mongoose");
Enter fullscreen mode Exit fullscreen mode

Connect to your mongo client by adding the below lines to your express server.

const PORT = process.env.PORT || 5000;

mongoose.connect(``,{
    useNewUrlParser:true,
    useUnifiedTopology:true
}).then(()=>{
    app.listen(PORT, () => {
        console.log(`Server is running on ${PORT}`);
      })
}).catch(err=>{
    console.log(err)
})

Enter fullscreen mode Exit fullscreen mode

We are going to add the connection string to the empty template string, so quickly navigate to your cluster in mongo and click on connect an application and copy the connection string.
image
and paste that string so that the final code looks like this. Don't forget to replace with the actual one.

mongoose.connect(`mongodb+srv://Mehak:<password>@cluster0.xgyma.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`,{
    useNewUrlParser:true,
    useUnifiedTopology:true
}).then(()=>{
    app.listen(PORT, () => {
        console.log(`Server is running on ${PORT}`);
      })
}).catch(err=>{
    console.log(err)
})

Enter fullscreen mode Exit fullscreen mode

Now run your server and voila! it's done!!..

Creating a schema

Create a new user.js file and let's create a user schema there. We'll add two basic fields of username and password and export it. The code looks super simple.

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

Oldest comments (0)