DEV Community

Himanshupal0001
Himanshupal0001

Posted on

#2. Setting up server , Db connectivity and custom script☀

Below is the instructions to setting up the server and db connectivity.

Setting up server in server.js file 💻

  1. Create server.js file within the root folder and follow below code. Note that we are using express for the server if you want you can use node or any other lib you want.
const express = require('express')
const connectDB = require('./config/db');
const app = express();
connectDB();

const PORT = process.env.PORT || 5000;

app.get('/', (req, res) => res.send('API Test'))


app.listen(PORT, () => {
    console.log(`Server is running at ${PORT}`)
})

Enter fullscreen mode Exit fullscreen mode

For DB follow below instructions 💾

  • Create config folder
  • Create default.json file within config folder
  • Create db.json file within this folder
  • Now write below code

File system img

Image description

//default.json file
{
    "mongoURI": "mongodb+srv://<mongodb username>:<password>@app.i967k.mongodb.net/?retryWrites=true&w=majority"
}
Enter fullscreen mode Exit fullscreen mode
// db.js file

const mongoose = require('mongoose')
const config = require('config')
const db = config.get('mongoURI');

const connectDB = async () => {
    try {
        await mongoose.connect(db);
        console.log('Db connected ...');
    }
    catch (err) {
        console.log(err);
        process.exit(1);
    }
}

module.exports = connectDB;

Enter fullscreen mode Exit fullscreen mode

TO run all this add below in your package.json file (highlighted) and run command in terminal

Image description

  • npm run server

Top comments (0)