DEV Community

Cover image for Mongo and Node.js on local instance
AreAtomic
AreAtomic

Posted on

Mongo and Node.js on local instance

Use MongoDB locally

To do

For the MERN stack it can be great to use MongoDB locally. Mainly if your company proxy does not accept to run on cloud. To install MongoDB on local there is three main steps :

  • Download the installer
  • Install on local without services
  • Create databases for test

Download the installer

First step, the easiest one but it can be confusious. The server installer can be found at the following link https://www.mongodb.com/try/download/community. It will allow you to install mongo.exe (the mongo shell), mongod.exe (the mongo server), mongos.exe.

Installation

This one can be various following your needed. I will explain you how to install on Windows without services.
Firstly we will execute the installer and decoche the "Install MongoDB as a Service"
Mongo DB installer windows decoche as services option

Click next, and choose to install MongoDB Compass to have graphical tool for your databases.

First use of MongoDB locally

Create the database

For this step we will use MongoDB Compass. Open the service and connect it to your local server.
Connect to local instance of mongodb

Once your are connected you can create your first database. Click on

CREATE DATABASE

name it as you want.

  • Database Name : myDatabase
  • Collection Name : users

Note: all MongoDB collections needs a s at the end.

Connect your Node.js server

Note: For this step we will simplify the configuration to make it easy but that does not respect best pratices of express configuration.

On your index.js file you will need to create your express instance and your mongoose connection.

const express = require('express')
const mongoose = require('mongoose')
const db = "mongodb://localhost:27017/myDatabase"

// Connection function
const connectDB = async () => {
    try{
        await mongoose.connect(db, {
            useNewUrlParser: true,
            useCreateIndex: true,
            useFindAndModify: false,
            useUnifiedTopology: true,
        })

        console.log('MongoDB successfully connected') 
    } catch (err) {
        console.error(err.message)
        process.exit(1)
    }
}

// Create server instance
const server = express()

// Creation of connection
connectDB()

// Import your routers
server.use('/api', require('./routes/root'))
Enter fullscreen mode Exit fullscreen mode

That's done you know how to create an local instance of MongoDB and to make your Node.js server running on it.

Discussion (2)

Collapse
vishalraj82 profile image
Vishal Raj

@areatomic I would always always use docker to get this setup done in my machine. Would be pretty easy to manage.

Collapse
areatomic profile image
AreAtomic Author

@vishalraj82 yes it's pretty easy to manage and to deploy with docker.