DEV Community

loading...

Connect your node app to MongoDB in ten easy steps

Hans
Father of one, environmentalist, runner , round-earther, nerd
・1 min read
  1. npm init -> entry point: server.js

  2. create file "server.js" in project root

  3. npm install mongoose express config nodemon

  4. in package.json add script "start":"nodemon"

{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"nodemon"
},
"author": "",
"license": "ISC",
"dependencies": {
"config": "^3.2.4",
"express": "^4.17.1",
"mongoose": "^5.8.7",
"nodemon": "^2.0.2"
}
}

  1. in project root -> make folder "config"

  2. in folder "config" make two files -> "db.js" and "default.json"

  3. in file "default.json" add the link with your mongodb credentials

{
"MongoURI":"mongodb+srv://username:yourpassword@aquacontrol-atxjt.mongodb.net/test?retryWrites=true&w=majority"
}

  1. in file "db.js" - add the following:

const mongoose = require('mongoose');
const config = require('config');
const database = config.get("MongoURI");

const connectDB = async () => {
try {
await mongoose.connect(database, {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log('Connected to mongoDB');
} catch (err) {
console.error(err.message);
process.exit(1);

}
Enter fullscreen mode Exit fullscreen mode

};

module.exports = connectDB;

  1. in "server.js" - add the following:

const express = require('express');
const app = express();

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(Server started on port ${PORT}));
/*

  • Connecting to mongoDB */ const connectDB = require('./config/database'); connectDB(); app.use(express.json({ extended: false }));

module.exports = connectDB;

  1. npm start

B

Discussion (0)