Read / Write File to API Data Base in MongoDB

 const express=require("express");

const bodyParser=require('body-parser');
const morgan=require('morgan');
const mongoose=require('mongoose');


const app=express();
app.use(morgan('tiny'));


const productSchema=mongoose.Schema({
    name: String,
    image: String,
    countInStock :{
        type: Number,
        required: true
    }
})

const Product=mongoose.model('Product',productSchema);

require('dotenv/config');

const api=process.env.API_URL;

// Middleware
app.use(bodyParser.json());






app.get(`${api}/products`, async (req,res)=>{
 
    const productList=await Product.find();

    res.send(productList);

    if(!productList){
        res.status(500).json({success: false})
    }
})





app.post(`${api}/products`,(req, res)=>{

    const product =new Product({
        name: req.body.name,
        image: req.body.image,
        countInStock: req.body.countInStock

    })

    product.save().then((createdProduct=>{
        res.status(201).json(createdProduct)
    })).catch((err)=>{
            res.status(500).json({
                error:err,
                success:false,
             
        })
    })

})



mongoose.connect(process.env.CONNECTION_STRING,{
    useNewUrlParser:true,
    useUnifiedTopology:true,
    dbName:'eshop-database'
})

.then(()=>{
    console.log("The database Connection is ready now......");
})
.catch((err)=> {

    console.log(err)

})
app.listen(3000,()=>{

 
    // console.log(product);
    // console.log("Now start my API is ",api);
    console.log("The Server is running http://localhost:4000");
})

Post a Comment

0 Comments