NodeJS MongoDB
server.js
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config({ path: './config.env' });
const app = require('./app'); // Require the Express app from app.js
const DB = process.env.DATABASE;
// Connect to the database--------------------------------------
mongoose
.connect("mongodb://localhost:27017/nikedb", {
useNewUrlParser: true,
useUnifiedTopology: true,
// Other options if needed
})
.then(() => {
console.log('Database connection successful');
})
.catch((err) => {
console.error('Database connection error:', err);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App running on port ${port}`);
});
app.js//////////////////////////////////////////////
const express = require('express');
const app = express()
const port = 4000
const shoesRoute = require('./routes/route');
app.use(express.json())
app.use((req, res, next) => {
req.reqTime = new Date().toISOString()
next()
})
app.use('/api', shoesRoute)
module.exports = app;
routes>route.js//////////////////////////////////////
cotroller>controller.js////////////////////////////////////////////
const express = require('express');
const shoesRoute = express.Router()
const { deleteShoes, updateShoes, getShoesById, AddShoes, getAllShoes, checkBody } = require("../controller/shoe.controller")
shoesRoute.get('/v1/shoes', getAllShoes)
shoesRoute.post('/v1/shoes',
// checkBody,
AddShoes)
shoesRoute.get('/v1/shoes/:id', getShoesById)
shoesRoute.put('/v1/shoes/:id', updateShoes);
shoesRoute.delete('/v1/shoes/:id', deleteShoes);
module.exports = shoesRoute
const fs = require('fs');
const shoes = require('../models/nike.model')
const data = JSON.parse(fs.readFileSync(`${__dirname}/../dev-data/data.json`))
const getAllShoes = (req, res) => {
res.status(200).json({
status: 'sucess',
requestedAt: req.reqTime,
length: data.length,
data: {
data
}
})
}
const AddShoes = async (req, res) => {
// debugger;
try {
const newShoes = await shoes.create(req.body)
res.status(200).json({
status: 'sucess',
length: data.length,
data: {
newShoes
}
})
} catch (err) {
res.status(400).json({
status: "fail",
message: 'Price is missing in the request body.'
});
}
}
const getShoesById = (req, res) => {
const id = req.params.id * 1
const shoes = data.find((el) => el.id === id)
if (id > data.length) {
return res.status(404).json({
status: 'fail',
message: 'invalid id'
})
}
res.status(201).json({
status: 'sucess',
length: data.length,
data: {
shoes
}
})
}
const updateShoes = (req, res) => {
const id = req.params.id * 1;
const shoesIndex = data.findIndex((el) => el.id === id);
if (shoesIndex === -1) {
return res.status(404).json({
status: 'fail',
message: 'Invalid id'
});
}
data[shoesIndex] = { ...data[shoesIndex], ...req.body };
res.status(200).json({
status: 'success',
data: {
shoes: data[shoesIndex]
}
});
}
const deleteShoes = (req, res) => {
const id = req.params.id * 1;
const shoesIndex = data.findIndex((el) => el.id === id);
if (shoesIndex === -1) {
return res.status(404).json({
status: 'fail',
message: 'Invalid id'
});
}
data[shoesIndex] = "";
res.status(200).json({
status: 'success',
data: {
shoes: data[shoesIndex]
}
});
}
module.exports = {
deleteShoes, updateShoes, getShoesById, AddShoes, getAllShoes,
// checkBody
}
models>nike.model.js
const mongoose = require('mongoose');
const NikeSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'obj must have name'],
unique: true
},
price: {
type: String,
required: [true, 'obj must have price']
},
images: Array
});
const shoes = mongoose.model('products', NikeSchema);
module.exports = shoes;
Comments
Post a Comment