Create your own RESTful API | handling POST request using NodeJS & MongoDB
MongoDB Express connection with the help of mongoose
src/app.jsconst express = require("express");require("./db/conn");const Student = require("./models/students");const app = express();const port = process.env.PORT || 8000;// use express.jsonapp.use(express.json());// define rootapp.get("/",(req, res)=>{res.send("home page")})// createapp.post("/students",(req,res)=>{console.log(req.body);const user = new Student(req.body);user.save().then(()=>{res.status(201).send(user)}).catch((e)=>{res.status(400).send(e);})// res.send("hello from the other side.");})app.listen(port, ()=>{console.log(`connecting port ${port}`)});// You DO NOT NEED express.json() and express.urlencoded()// for GET Requests or DELETE Requests. We only need it for// post and put req.// express.json() isa method inbuilt in express to recognize the// incomming Request Object as a JSON object.// This method is called as a middleware in your application using// the code: app.use(express.json());
// async functionapp.post("/students", async(req, res)=>{try{const user = new Student(req.body);const result = await user.save();res.status(201).send(result)}catch{res.status(400).send(e);}})
const mongoose = require("mongoose");mongoose.connect("mongodb://localhost:27017/students-api",{// useCreateIndex:true,useNewUrlParser: true,useUnifiedTopology:true}).then(()=>{console.log("Connection successful");}).catch((e)=>{console.log("failed connection",e)});
[nodemon] starting `node src/app.js` connecting port 8000 Connection successfulCreate Schema, collection and export it
src/models/student.js
const mongoose = require("mongoose");const validator = require("validator");// define schemaconst studentSchema = new mongoose.Schema({name : {type:String,required: true,minlength:3},email : {type: String,required:true,unique:[true,"Email id already present"],validate(value){if(!validator.isEmail(value)){throw new Error("Invalid Error")}}},phone:{type:Number,min:10,required:true,},address:{type:String,required:true}})// create a new collectionconst Student = new mongoose.model("Student", studentSchema);module.exports = Student;
Post a Comment