You are on page 1of 5

--Intial steps

----Make a folder named backend


----run cmd: npm init
{ give name, discription }
----run cmd: npm i express
----run cmd: npm mongoose
----run cmd: npm install bcryptjs
----run cmd: npm install jsonwebtoken
----run cmd: npm install --save-dev nodemon
----make file index.js(entery point)

(then change gitignore)


----Open MongoDb Compass and copy connection string
----Make db.js (it will be use to connect to data base)
-------inside db.js

const mongoose = require('mongoose');


const mongoURI = "mongodb://localhost:27017"

const connectToMongo = ()=>{


mongoose.connect(mongoURI,()=>console.log("connected to mongo
successfully"))
}

module.exports = connectToMongo;

-------index.js

const connectToMongo = require('./db')


connectToMongo();
----now to run follow the following

If you want to use the locally installed version,


rather than installing globally then you can create a
script in your package.json

"scripts": {
"serve": "nodemon index.js"
},

and then use


npm run serve
OR
node index.js

----now Add boiler plate code


const express = require("express");
const app = express();
const port = 3000;

app.get("/", (req, res) => {


res.send("Hello World!");
});

app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
<<----------setup completed---------->>
--file structure
----backend
------models (for mongoose models)
------routes (for routes)

--what is models and mongoose?


MongoDB:

--models basic format(namme start with uppercase)


const mongoose = require('mongoose');
const { Schema } = mongoose;
const userData = new Schema({
title: {type: String, required:true}, // String is shorthand for
{type: String}
username: {type: String, required:true, unique: true},
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});

//to make sure unique content based on parameters like email, username
//one way to that but we will not use it to do so
const User = mongoose.model('userdata', userData);
User.createIndexes();
module.exports = User

--Routes basic format(name in lowercase)

const express = require('express');


const router = express.Router();
const User = require('../models/User')

// Create a User using: POST '/api/user' Dosn't require Auth

router.post('/', (req,res)=>{
//make end-point here
console.log(req.body);
const user = User(req.body);
user.save();
res.send(req.body);

})

module.exports = router

--In index.js add these

app.use(express.json())
//Available routes(using app.use linking routes)
app.use('/api/<>',require('.routes/<route_name>'))

app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});

--Express validator
cmd: npm install --save express-validator
----then import below files in route file
const { body, validationResult } = require('express-validator')

----Note add header in Thunder client request of Conten-type application/json

--Example Code of all basic files

--Models
----Userdata.js

const mongoose = require("mongoose");


const { Schema } = mongoose;
const userData = new Schema({
name: { type: String, required: true },
username: { type: String, required: true },
dob: { type: Date },
password: { type: String, required: true },
});

const User = mongoose.model('userdata', userData);


module.exports = User

--Routes
----userinfo.js

const express = require("express");


const router = express.Router();
const User = require("../models/Userdata");
const { body, validationResult } = require("express-validator");
const bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
const pwt_key = "abcdefgh";

<------------------To add data to database------------------>


router.post("/signup", [body("password").isLength({ min: 8 })], async (req, res) =>
{
//checking for basic errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

try {
//checking weather the same email exist or not
let user = await User.findOne({ username: req.body.username });
if (user) {
return res.status(400).json({ error: "username already exist" });
};
const salt = await bcrypt.genSalt(10);
const seqPass = await bcrypt.hash(req.body.password, salt);
user = await User.create({
name: req.body.name,
password: seqPass,
username: req.body.username,
dob: req.body.dob,
});
//.then(user => res.json(user)).catch(e=>{console.log(e);
res.json({error:"unique value for emial"})});
const data = {
user:{
id: user.id
}
}
let token = jwt.sign(data,pwt_key)
res.json(token);
}
catch(error){console.error(error.message)};
});

<------------------To verfify username and password from database while


login------------------>
router.post("/signin", [body("password").exists()], async (req, res) => {
//checking for basic errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

try {
//checking weather the same email exist or not
let user = await User.findOne({ username: req.body.username });
if (!user) {
return res.status(400).json({ error: "Enter valide credentials" });
};

const { username, password } = req.body;


const passflag = await bcrypt.compare(password, user.password);
//.then(user => res.json(user)).catch(e=>{console.log(e);
res.json({error:"unique value for emial"})});
const data = {
user:{
id: user.id
}
}
let logintoken = jwt.sign(data,pwt_key)
res.json({logintoken});
}
catch(error){console.error(error.message)};
});
module.exports = router;

--db.js

const mongoose = require('mongoose');


const mongoURI = "mongodb://localhost:27017/usersdatabase"

const connectToMongo = ()=>{


mongoose.connect(mongoURI,()=>console.log("connected to mongo successfully"))
}

module.exports = connectToMongo;

--index.js

const connectToMongo = require("./db");

const express = require("express");


const app = express();
const port = 5000;

//Availble routes
app.use(express.json())
app.use('/api/user', require('./routes/userinfo'));

app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});

connectToMongo();

You might also like