const express = require("express"); const app = express(); const mongoose = require("mongoose"); const bodyParser = require("body-parser"); mongoose.connect("mongodb://127.0.0.1:27017/datasbase").then(() =>{ console.log("Mongodb Connected"); }).catch((err) =>{ console.log(err); }); app.use(bodyParser.urlencoded({extended: false})); app.use(express.json()); const productSchema = new mongoose.Schema({ _id: Number, name: String, price: Number }); const productModel = new mongoose.model("data", productSchema); //product create app.post("/api/v1/product/new", async (req, res) =>{ const productCreate = await productModel.create(req.body); res.status(201).json({ success: true, productCreate }); }); //products find app.get("/api/v1/products", async (req, res) =>{ const productFInd = await productModel.find(); res.status(200).json({ success: true, productFInd }); }); //product update app.put("/api/v1/product/:id", async (req, res) =>{ let productUpdate = await productModel.findById(req.params.id); if(!productUpdate){ return res.status(500).json({ success: false, message: "product not found" }) } productUpdate = await productModel.findByIdAndUpdate(req.params.id, req.body, {new: true, useFindAndModify: false, runValidators: true }); res.status(200).json({ success: true, productUpdate }); }); //delete product app.delete("/api/v1/product/:id", async(req, res) =>{ let productDelete = await productModel.findById(req.params.id); if(!productDelete){ return res.status(500).json({ success: false, message: "product not found" }) } await productModel.findByIdAndDelete(req.params.id); res.status(200).json({ success: true, message: "product deleted" }); }); app.listen(4500, () =>{ console.log("Server is working"); });
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter