Question: Hello . The code does not seem to be working completely. The state is not being persisted. Here are the requirements: The data has to

Hello . The code does not seem to be working completely. The state is not being persisted.
Here are the requirements:
The data has to be persistent.
Connect to your database
Create a schema for your data. You are now required to add a picture to your data... Integrate this into the information you show, save, edit...
Create the model
Complete the post, put and delete requests using mongo to make the changes to the data persistent.
Continue to validate your data via Joi.
The pictures should work for the whole session.
const express = require('express');
const cors = require('cors');
const multer = require('multer');
const mongoose = require('mongoose');
const Joi = require('joi');
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
const mongoURI = process.env.MONGODB_URI || 'mongodb://localhost:27017/gearInventory';
mongoose
.connect(mongoURI,{ useNewUrlParser: true, useUnifiedTopology: true })
.then(()=> console.log('MongoDB connected successfully'))
.catch((err)=> console.error('MongoDB connection error:', err));
const gearSchema = new mongoose.Schema({
name: { type: String, required: true },
brand: { type: String, required: true },
price: { type: Number, required: true },
img_name: { type: String },// Updated to support file uploads
rating: { type: Number },
features: [String],
});
const Gear = mongoose.model('Gear', gearSchema);
const storage = multer.diskStorage({
destination: (req, file, cb)=>{
cb(null,'./public/images/');
},
filename: (req, file, cb)=>{
cb(null, Date.now()+'-'+ file.originalname);
},
});
const upload = multer({ storage });
const itemSchema = Joi.object({
name: Joi.string().required(),
brand: Joi.string().required(),
price: Joi.number().required(),
img_name: Joi.string().optional(),
rating: Joi.number().optional(),
features: Joi.array().items(Joi.string()).optional(),
});
// GET Route
app.get('/api/gear', async (req, res)=>{
try {
const items = await Gear.find();
res.json(items);
} catch (err){
res.status(500).json({ success: false, message: 'Failed to fetch gear items' });
}
});
// POST Route with file upload
app.post('/api/gear', upload.single('img_name'), async (req, res)=>{
const bodyData ={...req.body, img_name: req.file ? req.file.filename : null };
const { error }= itemSchema.validate(bodyData);
if (error){
return res.status(400).json({ success: false, message: error.details[0].message });
}
try {
const newItem = new Gear(bodyData);
await newItem.save();
res.status(201).json({ success: true, newItem });
} catch (err){
res.status(500).json({ success: false, message: 'Failed to add gear item' });
}
});
// PUT Route with file upload
app.put('/api/gear/:id', upload.single('img_name'), async (req, res)=>{
const bodyData ={...req.body, img_name: req.file ? req.file.filename : null };
const { error }= itemSchema.validate(bodyData);
if (error){
return res.status(400).json({ success: false, message: error.details[0].message });
}
try {
const updatedItem = await Gear.findByIdAndUpdate(req.params.id, bodyData, { new: true });
if (!updatedItem){
return res.status(404).json({ success: false, message: 'Item not found' });
}
res.json({ success: true, updatedItem });
} catch (err){
res.status(500).json({ success: false, message: 'Failed to update gear item' });
}
});
// DELETE Route
app.delete('/api/gear/:id', async (req, res)=>{
try {
const deletedItem = await Gear.findByIdAndDelete(req.params.id);
if (!deletedItem){
return res.status(404).json({ success: false, message: 'Item not found' });
}
res.json({ success: true, message: 'Item deleted successfully' });
} catch (err){
res.status(500).json({ success: false, message: 'Failed to delete gear item' });
}
});
const PORT = process.env.PORT ||4000;
app.listen(PORT,()=> console.log(`Listening on port ${PORT}...`));

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!