Was making a RESTful API and was working as expected. I was using postman and mongodb, and made requests to work around. But now only Delete and Get requests are working, Update and create requests are returning that these "fields are required" though they are not empty. This was working fine until I added router.
const express = require("express");
require("./db/conn");
const Student = require("./models/students");
const studentRouter = require("./routers/stds");
// Environment Variables
const app = express();
const port = process.env.PORT || 8000;
// Calling Router
app.use(studentRouter);
// Middleware
app.use(express.json());
// Listening to port
app.listen(port, () => {
console.log(`Connection at ${port}`);
});
// Creating Router
const express = require("express");
const router = new express.Router();
const Student = require("../models/students");
// Creating URLs
router.get("/", (req, res) => {
res.send("Hello World");
});
// Creating data
router.post("/students", async (req, res) => {
try {
const user = new Student(req.body);
const createUser = await user.save();
console.log(createUser);
res.status(201).send(createUser);
} catch (e) {
res.status(400).send(e);
}
});
// Reading data
router.get("/students", async (req, res) => {
try {
const studentsData = await Student.find();
if (!studentsData) {
return res.status(404).send();
} else {
res.send(studentsData);
}
} catch (e) {
res.send(e);
}
});
// Reading data using IDs
router.get("/students/:id", async (req, res) => {
try {
const _id = await req.params.id;
const studentData = await Student.find({ _id });
res.send(studentData);
} catch (e) {
res.status(500).send(e);
}
});
// Update Student's Data by ID
router.patch("/students/:id", async (req, res) => {
try {
const _id = req.params.id;
const updateStudents = await Student.findByIdAndUpdate({ _id },
req.body,
{
new: true
});
res.send(updateStudents);
} catch (e) {
res.status(400).send(e);
}
});
// Delete Student's Data by I
router.delete("/students/:id", async (req, res) => {
try {
const id = req.params.id;
const deleteStudent = await Student.findByIdAndDelete({ id });
if (!id) {
return res.status(400).send();
}
else {
res.send(deleteStudent);
}
} catch (e) {
res.status(500).send(e);
}
})
module.exports = router;
My Schema file.
const mongoose = require("mongoose");
const validator = require("validator");
const studentSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 3
},
email: {
type: String,
required: true,
unique: [true, "Already Exists"],
validate(value) {
if (!validator.isEmail(value)) {
throw new Error("Invalid Email")
}
}
},
phone: {
type: Number,
minlength: 10,
required: true,
unique: true
},
address: {
type: String,
required: true
}
});
// creating new collection using model
const Student = new mongoose.model("Student", studentSchema);
module.exports = Student;
Inputs are given but it doesn't takes it as one
Please ask if need more information...
CodePudding user response:
You are sending data to your router without parsing it first.
// Calling Router
app.use(studentRouter);
// Middleware
app.use(express.json());
This should be other way around
// Middleware
app.use(express.json());
// Calling Router
app.use(studentRouter);