Question: What code changes do I need to make here to handle the DataForm? Thank you. const express = require ( express ) ;
What code changes do I need to make here to handle the DataForm? Thank you.
const express requireexpress;
const cors requirecors;
const multer requiremulter;
const mongoose requiremongoose;
const Joi requirejoi;
const app express;
app.usecors;
app.useexpressjson;
app.useexpressstaticpublic;
const mongoURI process.env.MONGODBURI "mongodb:localhost:gearInventory;
mongoose.connectmongoURI useNewUrlParser: true, useUnifiedTopology: true
then console.logMongoDB connected successfully"
catcherr console.errorMongoDB connection error:", err;
const gearSchema new mongoose.Schema
name: type: String, required: true
brand: type: String, required: true
price: type: Number, required: true
imgname: type: String
rating: type: Number
features: String
;
const Gear mongoose.modelGear gearSchema;
const storage multer.diskStorage
destination: req file, cb
cbnullpublicimages;
filename: req file, cb
cbnull Date.now file.originalname;
;
const upload multer storage ;
const itemSchema Joi.object
name: Joi.stringrequired
brand: Joi.stringrequired
price: Joi.numberrequired
imgname: Joi.stringoptional
rating: Joi.numberoptional
features: Joi.arrayitemsJoistringoptional
;
app.getapigear async req res
try
const items await Gear.find;
res.jsonitems;
catch err
res.statusjson success: false, message: "Failed to fetch gear items" ;
;
app.postapigear async req res
const error itemSchema.validatereqbody;
if error
return res.statusjson success: false, message: error.detailsmessage ;
try
const newItem new Gearreqbody;
await newItem.save;
res.statusjson success: true, newItem ;
catch err
res.statusjson success: false, message: "Failed to add gear item" ;
;
app.putapigear:id async req res
const error itemSchema.validatereqbody;
if error
return res.statusjson success: false, message: error.detailsmessage ;
try
const updatedItem await Gear.findByIdAndUpdatereqparams.id req.body, new: true ;
if updatedItem
return res.statusjson success: false, message: "Item not found" ;
res.json success: true, updatedItem ;
catch err
res.statusjson success: false, message: "Failed to update gear item" ;
;
app.deleteapigear:id async req res
try
const deletedItem await Gear.findByIdAndDeletereqparams.id;
if deletedItem
return res.statusjson success: false, message: "Item not found" ;
res.json success: true, message: "Item deleted successfully" ;
catch err
res.statusjson success: false, message: "Failed to delete gear item" ;
;
const PORT process.env.PORT ;
app.listenPORT console.logListening on port $PORT;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
