Connecting MongoDB MongoClient with Node Express Globally


Posted 1 week ago by Ryan Dhungel

Category: MongoDB Server Express JS Node

Viewed 54 times

Estimated read time: 1 minute

Course of the day!

MERN Stack Ultimate Authentication with Facebook Google and more

MERN Stack Ultimate Authentication with Facebook Google and more

const express = require('express');
const app = express();
const morgan = require('morgan');
const MongoClient = require('mongodb').MongoClient;

const port = process.env.PORT || 8000;
const mongo_uri = 'mongodb://localhost:27017';

// middlewares
app.use(morgan('dev'));

MongoClient.connect(mongo_uri, { useNewUrlParser: true })
    .then(client => {
        const db = client.db('nodeapi'); // db
        // make db available globally in express app
        app.locals.db = db;
    })
    .catch(error => console.error(error));

// routes
app.get('/', (req, res) => {
    const collection = req.app.locals.db.collection('posts'); // collection
    collection
        .find({})
        .toArray()
        .then(response => res.status(200).json(response))
        .catch(error => console.error(error));
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});