npm init -> entry point: server.js
create file "server.js" in project root
npm install mongoose express config nodemon
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"
}
}
in project root -> make folder "config"
in folder "config" make two files -> "db.js" and "default.json"
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"
}
- 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);
}
};
module.exports = connectDB;
- 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;
- npm start
B
Top comments (0)