I have created a rest API using NodeJS, Express, and MongoDB. I can successfully create data and view them in the database using MongoDB Compass but can't get single data using Id generated. Whenever I try it gives me a 404 error.
Here is my code:
bootcamps.js (controller)
const Bootcamp = require('../models/Bootcamp')
exports.getBootcamps = async (req, res, next) =>
{
try {
const bootcamps = await Bootcamp.find()
res.status(200).json({success: true, count: bootcamps.length, data: bootcamps})
} catch (error) {
res.status(400).json({success: false})
}
}
exports.getBootcamp = async (req, res, next) =>
{
try {
const bootcamp = await Bootcamp.findById({_id: req.params.id})
if (!bootcamp)
{
return res.status(400).json({success: false})
}
res.status(200).json({success: true, data: bootcamp})
} catch (error) {
res.status(400).json({success: false})
}
}
exports.createBootcamps = async (req, res, next) =>
{
try
{
const bootcamp = await Bootcamp.create(req.body)
res.status(201).json({
success: true,
data: bootcamp,
msg: 'Bootcamp created'
})
} catch (error)
{
console.log(error)
res.status(400).json({success: false})
}
}
exports.updateBootcamp = async (req, res, next) =>
{
try {
const bootcamp = await Bootcamp.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true
});
if (!bootcamp)
{
return res.statuc(400).json({success: false})
}
res.status(200).json({ success: true, data: bootcamp })
} catch (error) {
return res.statuc(400).json({success: false})
}
}
exports.deleteBootcamp = async (req, res, next) =>
{
try {
const bootcamp = await Bootcamp.findByIdAndDelete(req.params.id);
if (!bootcamp)
{
return res.statuc(400).json({success: false})
}
res.status(200).json({ success: true, data: {} })
} catch (error) {
return res.statuc(400).json({success: false})
}
}
Bootcamp.js (model)
const mongoose = require('mongoose')
const BootcampSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please add a name'],
unique: true,
trim: true,
maxlength: [50, 'Name can not be more than 50 characters']
},
slug: String,
description: {
type: String,
required: [true, 'Please add a description'],
maxlength: [500, 'Name can not be more than 50 characters']
},
website: {
type: String,
match: [
/https?:\/\/(www\.)?[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)/,
"Please use a valid URL with HTTP or HTTPS"
]
},
phone: {
type: String,
maxlength: [20, 'Phone number can not be longer than 20 characters']
},
email: {
type: String,
match: [
/^\w+([\.-]?\w+)+#\w+([\.:]?\w+)+(\.[a-zA-Z0-9]{2,3})+$/,
'Please add a valid email address'
]
},
address: {
type: String,
required: [true, 'Please add an address']
},
location: {
type: {
type: String,
enum: ['Point'],
required: false
},
coordinates: {
type: [Number],
required: false,
index: '2dsphere'
}
},
formattedAddress: String,
street: String,
city: String,
state: String,
zipcode: String,
country: String,
careers: {
type: [String],
required: true,
enum: [
'Web Development',
'Mobile Development',
'UI/UX',
'Data Science',
'Business',
'Other'
]
},
averageRating: {
type: Number,
min: [1, 'Rating must be at least 1'],
max: [10, 'Rating can not be more than 10']
},
averageCost: Number,
photo: {
type: String,
default: 'no-photo.jpg'
},
housing: {
type: Boolean,
default: false
},
jobAssistance: {
type: Boolean,
default: false
},
jobGuarantee: {
type: Boolean,
default: false
},
acceptGi: {
type: Boolean,
default: false
},
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Bootcamp', BootcampSchema)
bootcamps.js (routes)
const express = require('express')
const { getBootcamp, getBootcamps, createBootcamps, updateBootcamp, deleteBootcamp } = require('../controllers/bootcamps')
const router = express.Router()
router.route('/').get(getBootcamps).post(createBootcamps)
router.route(':id').put(updateBootcamp).delete(deleteBootcamp).get(getBootcamp)
module.exports = router
index.js (entry file)
const express = require('express')
const dotenv = require('dotenv')
const morgan = require('morgan')
const connectDB = require('./config/db')
const colors = require('colors')
dotenv.config({ path: './config/config.env' })
connectDB()
const bootcamps = require('./routes/bootcamps')
const app = express();
app.use(express.json())
if (process.env.NODE_ENV === 'development')
{
app.use(morgan('dev'))
}
app.use('/api/v1/bootcamps', bootcamps)
const PORT = process.env.PORT || 5000
const server = app.listen(PORT, console.log(`Server is running in
${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold))
process.on(`unhandledRejection`, (err, promise) =>
{
console.log(`Error: ${err.message}`.red)
server.close(() => process.exit(1))
})
Found the error!
I forgot to add the '/' on the single route
Before:
router.route(':id').put(updateBootcamp).delete(deleteBootcamp).get(getBootcamp)
After:
router.route('/:id').put(updateBootcamp).delete(deleteBootcamp).get(getBootcamp)
Surprisingly the console and postman result didn't complain and point that out!
Related
Im trying to make an ecommerce app and the frontend is all done but when i place an order i get this message.
I rechecked every file but i cant find where its coming from. I followed the process from a udemy course but it just doesnt work. i got no response from the instructor and his code seems to work fine.
Here is the github master repo for the course.
I am stuck here for 10 days. HELP!
https://github.com/bluebits-academy/mern-stack-ecommerce
This is my Order.js
const mongoose = require('mongoose');
const orderSchema = mongoose.Schema({
orderItems: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'OrderItem',
required:true
}],
shippingAddress1: {
type: String,
required: true,
},
shippingAddress2: {
type: String,
},
city: {
type: String,
required: true,
},
zip: {
type: String,
required: true,
},
country: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
status: {
type: String,
required: true,
default: 'Pending',
},
totalPrice: {
type: Number,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
dateOrdered: {
type: Date,
default: Date.now,
},
})
orderSchema.virtual('id').get(function () {
return this._id.toHexString();
});
orderSchema.set('toJSON', {
virtuals: true,
});
exports.Order = mongoose.model('Order', orderSchema);
/**
Order Example:
{
"orderItems" : [
{
"quantity": 3,
"product" : "5fcfc406ae79b0a6a90d2585"
},
{
"quantity": 2,
"product" : "5fd293c7d3abe7295b1403c4"
}
],
"shippingAddress1" : "Flowers Street , 45",
"shippingAddress2" : "1-B",
"city": "Prague",
"zip": "00000",
"country": "Czech Republic",
"phone": "+420702241333",
"user": "5fd51bc7e39ba856244a3b44"
}
**/
This is my api for order. orders.js
const {Order} = require('../models/order');
const express = require('express');
const { OrderItem } = require('../models/order-item');
const router = express.Router();
router.get(`/`, async (req, res) =>{
const orderList = await Order.find().populate('user', 'name').sort({'dateOrdered': -1});
if(!orderList) {
res.status(500).json({success: false})
}
res.send(orderList);
})
router.get(`/:id`, async (req, res) =>{
const order = await Order.findById(req.params.id)
.populate('user', 'name')
.populate({
path: 'orderItems', populate: {
path : 'product', populate: 'category'}
});
if(!order) {
res.status(500).json({success: false})
}
res.send(order);
})
router.post('/', async (req,res)=>{
const orderItemsIds = Promise.all(req.body.orderItems.map(async (orderItem) =>{
let newOrderItem = new OrderItem({
quantity: orderItem.quantity,
product: orderItem.product
})
newOrderItem = await newOrderItem.save();
return newOrderItem._id;
}))
const orderItemsIdsResolved = await orderItemsIds;
const totalPrices = await Promise.all(orderItemsIdsResolved.map(async (orderItemId)=>{
const orderItem = await OrderItem.findById(orderItemId).populate('product', 'price');
const totalPrice = orderItem.product.price * orderItem.quantity;
return totalPrice
}))
const totalPrice = totalPrices.reduce((a,b) => a +b , 0);
let order = new Order({
orderItems: orderItemsIdsResolved,
shippingAddress1: req.body.shippingAddress1,
shippingAddress2: req.body.shippingAddress2,
city: req.body.city,
zip: req.body.zip,
country: req.body.country,
phone: req.body.phone,
status: req.body.status,
totalPrice: totalPrice,
user: req.body.user,
})
order = await order.save();
if(!order)
return res.status(400).send('the order cannot be created!')
res.send(order);
})
router.put('/:id',async (req, res)=> {
const order = await Order.findByIdAndUpdate(
req.params.id,
{
status: req.body.status
},
{ new: true}
)
if(!order)
return res.status(400).send('the order cannot be update!')
res.send(order);
})
router.delete('/:id', (req, res)=>{
Order.findByIdAndRemove(req.params.id).then(async order =>{
if(order) {
await order.orderItems.map(async orderItem => {
await OrderItem.findByIdAndRemove(orderItem)
})
return res.status(200).json({success: true, message: 'the order is deleted!'})
} else {
return res.status(404).json({success: false , message: "order not found!"})
}
}).catch(err=>{
return res.status(500).json({success: false, error: err})
})
})
router.get('/get/totalsales', async (req, res)=> {
const totalSales= await Order.aggregate([
{ $group: { _id: null , totalsales : { $sum : '$totalPrice'}}}
])
if(!totalSales) {
return res.status(400).send('The order sales cannot be generated')
}
res.send({totalsales: totalSales.pop().totalsales})
})
router.get(`/get/count`, async (req, res) =>{
const orderCount = await Order.countDocuments((count) => count)
if(!orderCount) {
res.status(500).json({success: false})
}
res.send({
orderCount: orderCount
});
})
router.get(`/get/userorders/:userid`, async (req, res) =>{
const userOrderList = await Order.find({user: req.params.userid}).populate({
path: 'orderItems', populate: {
path : 'product', populate: 'category'}
}).sort({'dateOrdered': -1});
if(!userOrderList) {
res.status(500).json({success: false})
}
res.send(userOrderList);
})
module.exports =router;
And this is my order-item.js
const mongoose = require('mongoose');
const orderItemSchema = mongoose.Schema({
quantity: {
type: Number,
required: true
},
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}
})
exports.OrderItem = mongoose.model('OrderItem', orderItemSchema);
Do comment if you need any more codes.
The error :
ValidationError : OrderItem validation failed : product : Cast to ObjectId failed for value "{..}" at path "product"
means that: the "product" property in OrderItem expect an ObjectId, you can see it in the schema :
const orderItemSchema = mongoose.Schema({
quantity: {
type: Number,
required: true
},
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}
})
but you're passing an object into it here :
let newOrderItem = new OrderItem({
quantity: orderItem.quantity,
product: orderItem.product //<------ orderItem.product is an object
})
newOrderItem = await newOrderItem.save();
I think it should be :
let newOrderItem = new OrderItem({
quantity: orderItem.quantity,
product: orderItem.product.id // we only need the id of product
})
newOrderItem = await newOrderItem.save();
You may need to log orderItem.product before creating a new OrderItem to ensure the data inside it.
I am trying to make API for restaurants and developed its controller and model as shown below.
Controller (restaurantData.js)
const restaurantData = require('../Models/restaurantData');
exports.getRestaurantData = (req, res) => {
console.log(req.params.city_id.toString())
restaurantData.find({
city_id: req.params.city_id.toString()
}).then(result => {
res.status(200).json({
message: "Restaurant Data",
restaurants: result
});
}).catch(error => {
res.status(500).json({
message: error
});
});
}
Model (restaurantData.js)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const restaurantSchema = new Schema({
_id: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
city_name:{
type: String,
required: true
},
city_id: {
type: String,
required: true
},
location_id: {
type: Number,
required: true
},
area: {
type: Number,
required: true
},
locality:{
type: String,
required: true
},
thumb: {
type: String,
required: true
},
cost:{
type: Number,
required: true
},
address:{
type: String,
required: true
},
mealtype:{
type: Number,
required: true
},
name:{
type: String,
required: true
},
cuisine:{
type: Number,
required: true
},
type:{
type: Array,
required: true
},
Cuisine:{
type: Array,
required: true
}
});
module.exports = mongoose.model('restaurantData', restaurantSchema, 'restaurantData');
router.js
const express = require('express');
const restaurantController = require('../Controllers/restaurantData');
const router = express.Router();
router.get('/restaurantData/:cityID',restaurantController.getRestaurantData);
module.exports = router;
app.js
const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const apiRouter = require('./Routes/router');
const port = 4005;
const app = express();
app.use(bodyparser.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers','Content-Type, Authorization');
next();
});
app.use('/api', apiRouter);
mongoose.connect(
'mongodb://127.0.0.1:27017/sampleRestaurant',
{ useNewUrlParser: true, useUnifiedTopology: true }
).then(success => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Server started at port ${port}`);
});
}).catch(error => {
console.log(error);
});
Problem is while running on Postman its showing the error "Cannot GET /api/restaurantData". Please share some ideas.
I found an error in your model where you ask for
req.params.city_id.toString()
which is not correct and necesary to convert to an String.
you should use this instead:
const restaurantData = require('../Models/restaurantData');
exports.getRestaurantData = (req, res) => {
const cityId = req.params.cityID;
console.log(cityId)
restaurantData.find({
city_id: cityId
}).then(result => {
res.status(200).json({
message: "Restaurant Data",
restaurants: result
});
}).catch(error => {
res.status(500).json({
message: error
});
});
}
the reason is because you require the parameter city_id instead of cityID, the one you use in your route:
router.get('/restaurantData/:cityID',restaurantController.getRestaurantData);
All my other routes are working fine but when i try to fetch employees from db it doesn't work, i tried different approach to fetch my employees i.e. using app.get method in app.js and it worked, but when i try to use it with controllers and routes it doesn't even hit the route! please help! thankyou!
app.js
const express = require('express')
const app = express();
const appUserRoute = require('./routes/appuserRoute')
const employeeRoute = require('./routes/employeeRoute')
require('./db/mongoose')
app.use(express.json())
if(process.env.NODE_ENV!=="production"){
app.use(morgan('dev'))
}
app.use('/appusers',appUserRoute)
app.use('/appusers/employees',employeeRoute)
//start server
app.listen(PORT,
console.log(`Server running in ${process.env.NODE_ENV } mode on port ${PORT}`.green)
)
employeeRoute.js
const express = require('express')
const router = express.Router();
const {getEmployees, getEmployee, createEmployee, updateEmployee, deleteEmployee } = require('../controllers/employeeController')
router
.route('/')
.get(getEmployees)
.post(createEmployee)
router
.route('/:id')
.get(getEmployee)
.patch(updateEmployee)
.delete(deleteEmployee)
module.exports = router
employeeController.js
const Employee = require('../Models/employee')
exports.getEmployees = async (req, res) => {
try {
const employees = await Employee.find({})
if(!employees){
res.status(404).json({
message:'Not Data Found!'
})
}
res.status(200).json({
message:'Data Found!',
data:employees
})
} catch (e) {
res.status(500).send()
}
}
mongoose.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/MagicInventory-api', {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
}).then(() => console.log("Connected".green))
.catch(err => console.log(err.red));
employee model
const mongoose = require('mongoose');
var validator = require('validator');
const employeeSchema = new mongoose.Schema({
firstName: {
type: String,
required: [true, 'please specify First Name'],
trim: true,
maxlength: [20, 'FirstName cannot be more than 20 characters!']
},
lastName: {
type: String,
trim: true,
// maxlength: [20, 'lastName cannot be more than 20 characters!']
},
email: {
type: String,
trim: true,
lowercase: true,
// unique: true,
// required: [true,'Email address is required'],
// validate: {
// validator: validator.isEmail,
// message: 'invalid email',
// }
},
maritalStatus: {
type: String,
// required:[true, 'Choose the Gender']
},
dateOfBirth: {
type: Date,
// required: [true, 'Date of Birth is required!']
},
profile: {
type: String,
lowercase: true
},
contactDetails: {
adressLine1: {
type: String
},
adressLine2: {
type: String
},
city: {
type: String
},
state: {
type: String
},
zipCode: {
type: Number
},
country: {
type: String
},
contact: {
type: Number,
match: [
/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
'Phone number is not valid!'
]
},
},
bankDetails:{
bankName:{
type:String,
},
accountNumber:{
type:Number
},
accountName:{
type:String
},
ifscCode:{
type:String
}
},
dateOfJoining:{
type: Date,
},
createdAt: {
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('Employee', employeeSchema)
The problem is solved! I made a mistake while writing routes!
the actual route should be :- app.use('/employees',employeeRoute);
This is my Profile Schema:
const mongoose = require('mongoose');
const ProfileSchema = new mongoose.Schema({
user: {
// Special field type because
// it will be associated to different user
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
company: {
type: String,
},
website: {
type: String,
},
location: {
type: String,
},
status: {
type: String,
required: true,
},
skills: {
type: [String],
required: true,
},
bio: {
type: String,
},
githubusername: {
type: String,
},
experience: [
{
title: {
type: String,
required: true,
},
company: {
type: String,
required: true,
},
location: {
type: String,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
education: [
{
school: {
type: String,
required: true,
},
degree: {
type: String,
required: true,
},
fieldofstudy: {
type: String,
required: true,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
social: {
youtube: {
type: String,
},
twitter: {
type: String,
},
facebook: {
type: String,
},
linkedin: {
type: String,
},
instagram: {
type: String,
},
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Profile = mongoose.model('profile', ProfileSchema);
This is my view api. It doesn't work. it only return Cast to ObjectId failed for value { 'experience._id': '5edcb6933c0bb75b3c90a263' } at path _id for model profile
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
const exp = await Profile.findById({
'experience._id': req.params.viewexp_id,
});
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
How can I fix this? I tried looking at the stackoverflow of the same errors. still it doesn't seem to work.
and this is what I am trying to hit
The problem is that you have to convert your string _id to mongoose object id using this function mongoose.Types.ObjectId and my suggestion is to use findOne function instead of findById,
var mongoose = require('mongoose');
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
let id = mongoose.Types.ObjectId(req.params.viewexp_id);
const exp = await Profile.findOne(
{ "experience._id": req.params.viewexp_id },
// This will show your sub record only and exclude parent _id
{ "experience.$": 1, "_id": 0 }
);
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
var mongoose = require('mongoose');
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
const exp = await Profile.findOne({
'experience._id': mongoose.Types.ObjectId(req.params.viewexp_id),
});
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
You are saving object id . but your param id is string. convert it in ObjectId. Please check my solution.
router.post(
"/",
[
auth,
[
check("status", "status is required").not().isEmpty(),
check("skills", "skills is required").not().isEmpty(),
],
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
company,
website,
location,
bio,
status,
githubuername,
skills,
youtube,
facebook,
twitter,
instagram,
linkedin,
} = req.body;
const profileFileds = {};
profileFileds.user = req.user.id;
if (company) profileFileds.company = company;
if (website) profileFileds.website = website;
if (location) profileFileds.location = location;
if (bio) profileFileds.bio = bio;
if (status) profileFileds.status = status;
if (githubuername) profileFileds.githubuername = githubuername;
if (skills) {
profileFileds.skills = skills.split(",").map((skill) => skill.trim());
}
//Build profile object
profileFileds.social = {};
if (youtube) profileFileds.social.youtube = youtube;
if (twitter) profileFileds.social.twitter = twitter;
if (facebook) profileFileds.social.facebook = facebook;
if (linkedin) profileFileds.social.linkedin = linkedin;
if (instagram) profileFileds.social.instagram = instagram;
try {
let profile = await Profile.findOne({ user: req.user.id });
if (profile) {
//update
profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFileds },
{ new: true }
);
return res.json(profile);
}
//Create profile
profile = new Profile(profileFileds);
await profile.save();
res.json(profile);
} catch (err) {
console.error(err.message);
res.status(500).send("server Error");
}
}
);
I want to export two schemas in my model js file and I want use in router js file. I have tried this code below.
This is my certification.js file(models)
const mongoose = require('mongoose');
const Schema = mongoose.schema;
const requestCertificationSchema = mongoose.Schema({
userid: { type: String, require: true },
certName: { type: String, require: true },
certType: { type: String, require: true },
examName: { type: String, require: true },
examYear: { type: String, require: true },
examIndex: { type: String, require: true },
reqDate: {type: String, require: true},
state: { type: String, require: true}
});
const requestCertification = mongoose.model("requestCertification", requestCertificationSchema);
module.exports.saveRequest = function (newRequestCertification, callback) {
newRequestCertification.save(callback);
};
const requestStudentstatusSchema = mongoose.Schema({
studentName: { type: String, require: true },
admissionNum: { type: String, require: true },
dateofAdmission: { type: String, require: true },
currentStatus: { type: String, require: true },
description: { type: String, require: true },
});
const requestStudentstatus= mongoose.model("requestStudentstatus", requestStudentstatusSchema);
module.exports = {
requestCertification: requestCertification,
requestStudentstatus: requestStudentstatus
}
This is my certification.js file(routes)
const router = express.Router();
const Certification = require('../models/certification');
const config = require('../config/database');
router.post("/requestCert", function (req, res) {
const newRequest = new requestCertification({
userid: req.body.userid,
certName: req.body.certName,
certType: req.body.certType,
examName: req.body.examName,
examYear: req.body.examYear,
examIndex: req.body.examIndex,
reqDate:req.body.reqDate,
state: req.body.state
});
console.log(newRequest);
Certification.requestCertification.saveRequest(newRequest, function (err, request) {
if (err) {
res.json({ state: false, msg: "Data inserting Unsuccessfull..!" });
}
if (request) {
res.json({ state: true, msg: "Data inserted Successfully..!" });
}
});
});
When I call this url i have show this error! .
ReferenceError: requestCertification is not defined
Change this code to this one in routes/certification.js
const router = express.Router();
const {requestCertification} = require('../models/certification');
const {requestStudentstatus} = require('../models/certification');
const config = require('../config/database');
router.post("/requestCert", function (req, res) {
const newRequest = new requestCertification({
userid: req.body.userid,
certName: req.body.certName,
certType: req.body.certType,
examName: req.body.examName,
examYear: req.body.examYear,
examIndex: req.body.examIndex,
reqDate:req.body.reqDate,
state: req.body.state
});
// console.log(newRequest);
newRequest
.save()
.then(result => {
console.log(result)
res.json({ state: true, msg: "Data inserted Successfully..!" });
})
.catch(error => {
console.log(error)
res.json({ state: false, msg: "Data inserting Unsuccessfull..!" });
})
});
and delete the saveRequest() function in models/certification.js