Open mahendra785 opened 3 weeks ago
Develop an API route that allows authorized users to update business details in the database. This will enable users to modify existing business information as needed.
Express Route Handler Example:
const express = require('express');
const router = express.Router();
const Business = require('../models/businessModel'); // Assuming the schema is in `models/businessModel.js`
// PUT route to update business details
router.put('/businesses/:id', async (req, res) => {
try {
// 1. Extract the business ID from the route parameters.
const businessId = req.params.id;
// 2. Extract the updated business details from the request body.
const updatedDetails = req.body;
// 3. Find the business by ID and update it with the new details.
const updatedBusiness = await Business.findByIdAndUpdate(
businessId,
updatedDetails,
{ new: true, runValidators: true } // Options: return the updated document and run validators
);
// 4. Check if the business was found and updated.
if (!updatedBusiness) {
return res.status(404).json({ error: "Business not found." });
}
// 5. Return the updated business details in the response.
res.status(200).json(updatedBusiness);
} catch (error) {
// 6. Handle any errors (e.g., invalid ID format, database issues).
res.status(500).json({ error: "Server error. Please try again later." });
}
});
module.exports = router;
Develop an API route that allows users to update business details in the database. This will enable authorized users to modify existing business information as needed.