Connecting MongoDB MongoClient with Node Express Globally
Posted 3 years ago by Ryan Dhungel
Category: MongoDB Server Express JS Node
Viewed 2489 times
Estimated read time: 1 minute
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}`);
});