Mongo DB connect with node js

 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:Number
})

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

require('dotenv/config');

const api=process.env.API_URL;

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






app.get(`${api}/products`,(req,res)=>{
    // res.send("hello API world!");
    const product={
        id:1,
        name:'Anand Chaudhary',
        email:'apchaudhary8126@gmail.com'
    }
    res.send(product);
})





app.post(`${api}/products`,(req,res)=>{
    // res.send("hello API world!");
    const newProduct =req.body;
    console.log(newProduct);
    res.send(newProduct);
})



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