DEV Community

Cover image for Node js and Express js project setup
Nanda kishor palei
Nanda kishor palei

Posted on

Node js and Express js project setup

Explaining with example of create and get user
npm init

npm install express mongoose bcryptjs dotenv nodemon

Make 3 folders inside the src folder

  1. configs
  2. controllers
  3. model

two files at the top level

  • index.js
  • server.js

Create a MongoDB database to connect to your app

Open MongoDB

If You don’t have a database already created then follow below instructions

Or feel free to skip these instructions

from the left menu click on the database

click on Build a database

select the type of database you need ( for learning select free )

then click Create

click on create cluster

add a username and password ( do remember the password )

create user

scroll down and select cloud environment

then add an IP address by clicking Add My Current IP Address button

scroll down and click finish and close
Enter fullscreen mode Exit fullscreen mode

Then your database is ready to serve

click on the connect button on the current cluster

click on connect to your application

copy the link

mongodb+srv://nk45:<password>@cluster0.buxffaj.mongodb.net/?retryWrites=true&w=majority

use your recently created user and password

User - nkp45
password - Replace **<password>** with the user's password ( you created ). Ensure any option params are [URL encoded](https://dochub.mongodb.org/core/atlas-url-encoding).
Enter fullscreen mode Exit fullscreen mode

create a file db.js inside configs

db.js

const mongoose = require('mongoose');
mongoose.set('strictQuery', false);
const connect = () => {
  return mongoose.connect(
    'mongodb+srv://nkp45:<password>@cluster0.buxffaj.mongodb.net/?retryWrites=true&w=majority',
    {
      useUnifiedTopology: true,
      useNewUrlParser: true
    }
  );
};

module.exports = connect;
Enter fullscreen mode Exit fullscreen mode

index.js

const app = require('./server');
const connect = require('./src/configs/db');

const port = '8000';
app.listen(port, async () => {
  try {
    await connect();
    console.log('This server runs at port ' + port);
  } catch (e) {
    console.log(e.message);
  }
});
Enter fullscreen mode Exit fullscreen mode

server.js

require('dotenv').config();
const express = require('express');
const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use(express.static('public'));

const userController = require('./src/controllers/userController');
app.use('/users', userController);

module.exports = app;
Enter fullscreen mode Exit fullscreen mode

create a file userModel inside models

userModel.js

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema(
  {
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    roles: [
      {
        type: String,
        required: true,
        default: 'customer',
        enum: ['customer', 'admin', 'both']
      }
    ]
  },
  {
    versionKey: false,
    timestamps: true
  }
);

userSchema.pre('save', function (next) {
  if (!this.isModified('password')) return next();
  this.password = bcrypt.hashSync(this.password, 8);
  next();
});

userSchema.methods.checkPassword = function (password) {
  return bcrypt.compareSync(password, this.password);
};

const User = mongoose.model('user', userSchema);
module.exports = User;
Enter fullscreen mode Exit fullscreen mode

create a file userController inside the controller folder

userController.js

const express = require('express');
const router = express.Router();

const User = require('../model/userModel');

router.post('', async (req, res) => {
  try {
    const user = await User.create(req.body);
    return res.status(201).send(user);
  } catch (e) {
    console.log(e.message);
    return res.status(500).send(e.message);
  }
});

router.get('', async (req, res) => {
  try {
    const user = await User.find().lean().exec();
    return res.status(201).send(user);
  } catch (e) {
    console.log(e.message);
    return res.status(500).send(e.message);
  }
});

router.get('/:id', async (req, res) => {
  try {
    const user = User.findById(req.params.id).lean().exec();
  } catch (e) {
    console.log(e.message);
    return res.status(500).send(e.message);
  }
});

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

nodemon setup
Nodemon - it is a tool that helps develop Node. js based applications by automatically restarting the node application when file changes in the directory are detected. nodemon does not require any additional changes to your code or method of development. nodemon is a replacement wrapper for node .

"scripts": {
    "start": "nodemon index.js"
  },
Enter fullscreen mode Exit fullscreen mode

add this to package.json

That's all - nodemon start

Top comments (0)