I am having some trouble getting the sweetalert2 alerts to switch between successful operation alerts and errors. It is currently only showing the error alerts.
I am not quite sure where I am going wrong. My code is as follows:
- carsEdit.js
// Imported react libraries and hooks.
import React, { useState } from "react";
// Requiring Axios.
import axios from "axios";
// Imported components from React Bootstrap.
import {
Button,
Container,
Form,
FormGroup,
FormControl,
FormLabel,
} from "react-bootstrap";
// Imported icons from FontAwesome.
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPlus, faEdit, faTrashAlt } from "@fortawesome/free-solid-svg-icons";
// Imported Swal from sweetalert2.
import Swal from "sweetalert2";
/**
* @param {*} cars
* @param {*} setCars
* Created a search component with an input area, dropdown menu for the categories and a search button.
* Set the initial states of the prop values using the useState() hook.
*/
const CarEdit = ({ cars, setCars }) => {
const [id, setId] = useState("");
const [Model, setModel] = useState("");
const [Make, setMake] = useState("");
const [Owner, setOwner] = useState("");
const [Registration, setRegistration] = useState("");
const [Address, setAddress] = useState("");
const [previousOwners, setPreviousOwners] = useState("");
/**
* Assigned an event.preventDefault() method to ensure that the page is not refreshed once the create function is executed.
* Fetching the content from http://localhost:8080/api/create. Utilizing the Post method and added a header to set the content type to JSON.
* Added the necessary props to alocate values to and stringified the content to be added to the JSON file.
* If successful a modal (Sweetalert2 - Swal.fire) will appear to confirm success and the content will be added to the UI as objects.
* If unsuccessful a modal (Sweetalert2 - Swal.fire) will appear displaying an error. An error will occur if all the information is not
* entered as set in the backend/ server side and the content will be returned unchanged.
* @param {*} e Posting content to JSON as a string and returning the content as objects to the UI.
*/
const create = (e) => {
e.preventDefault();
axios
.post("cars/create", {
Model,
Make,
Owner,
Registration,
Address,
previousOwners,
})
.then((response) => {
Swal.fire({
imageUrl: "./images/success.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Success",
confirmButtonColor: "#007aff",
width: 400,
title: "SUCCESS!",
});
setCars(response.data);
})
.catch((error) => {
console.log(error);
Swal.fire({
imageUrl: "./images/exclamation.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
text: "User data missing",
}).then(function () {
window.location.reload();
});
});
};
/**
* Assigned an event.preventDefault() method to ensure that the page is not refreshed once the update function is executed.
* Fetching the content from http://localhost:8080/api/update/ (an ID should be entered to update that specific car). Utilizing the
* Put method and added a header to set the content type to JSON.
* Added the necessary props to alocate values to and stringified the content to be added to the JSON file.
* If successful a modal (Sweetalert2 - Swal.fire) will appear to confirm success and the content will be added to the UI as objects.
* If unsuccessful a modal (Sweetalert2 - Swal.fire) will appear displaying an error. An error will occur if all the information is not
* entered as set in the backend/ server side and the content will be returned unchanged.
* @param {*} e Updating content, that exists in the JSON file, as a string and returning the content as objects to the UI.
*/
const updateOne = (e) => {
e.preventDefault();
axios
.put(`cars/updateOne/${id}`, {
Model: Model,
Make: Make,
Owner: Owner,
Registration: Registration,
Address: Address,
previousOwners: previousOwners,
})
.then((response) => {
Swal.fire({
imageUrl: "./images/success.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Success",
confirmButtonColor: "#007aff",
width: 400,
title: "SUCCESS!",
});
setCars(response.data);
})
.catch((error) => {
console.log(error);
Swal.fire({
imageUrl: "./images/exclamation.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
text: "User data missing",
}).then(function () {
window.location.reload();
});
});
};
/**
* Assigned an event.preventDefault() method to ensure that the page is not refreshed once the update function is executed.
* Fetching the content from http://localhost:8080/api/update/ (an ID should be entered to update that specific car). Utilizing the
* Put method and added a header to set the content type to JSON.
* Added the necessary props to alocate values to and stringified the content to be added to the JSON file.
* If successful a modal (Sweetalert2 - Swal.fire) will appear to confirm success and the content will be added to the UI as objects.
* If unsuccessful a modal (Sweetalert2 - Swal.fire) will appear displaying an error. An error will occur if all the information is not
* entered as set in the backend/ server side and the content will be returned unchanged.
* @param {*} e Updating content, that exists in the JSON file, as a string and returning the content as objects to the UI.
*/
const updateMany = (e) => {
e.preventDefault();
axios
.put(`cars/updateMany/${Model}`, {
Make: Make,
Owner: Owner,
Registration: Registration,
Address: Address,
previousOwners: previousOwners,
})
.then((response) => {
console.log(response);
Swal.fire({
imageUrl: "./images/success.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Success",
confirmButtonColor: "#007aff",
width: 400,
title: "SUCCESS!",
});
setCars(response.data);
console.log(response.data);
})
.catch((error) => {
console.log(error);
Swal.fire({
imageUrl: "./images/exclamation.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
text: "User data missing",
}).then(function () {
window.location.reload();
});
});
};
/**
* Assigned an event.preventDefault() method to ensure that the page is not refreshed once the delete function is executed.
* Fetching the content from http://localhost:8080/api/delete/ (an ID should be entered to update that specific car). Utilizing the
* Delete method and added a header to set the content type to JSON.
* If successful a modal (Sweetalert2 - Swal.fire) will appear to confirm success and the content will be removed from the JSON file and UI.
* If unsuccessful a modal (Sweetalert2 - Swal.fire) will appear displaying an error.
* @param {*} e Deleting content that exists in the JSON file.
*/
const remove = (e) => {
e.preventDefault();
axios
.delete(`cars/delete/${id}`)
.then((response) => {
if (response.status === 200 && response.data === "Applied successfully")
Swal.fire({
imageUrl: "./images/success.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Success",
confirmButtonColor: "#007aff",
width: 400,
title: "SUCCESS!",
});
setCars(response.data);
})
.catch((error) => {
console.log(error);
Swal.fire({
imageUrl: "./images/exclamation.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
}).then(function () {
window.location.reload();
});
});
};
/**
* Added the handleChange() function to the onChange() event to set the new values of the props when values are entered into the input
* elements.
* Created buttons for the cars app. Passed onClick() events to create, update and delete cars.
* @returns Form with labels, input and button elements that can be used to add, update and delete cars.
*/
return (
<div>
<Container>
<Form className="d-flex flex-column">
<FormGroup>
<FormLabel htmlFor="id">ID:</FormLabel>
<FormControl
type="text"
name="id"
value={id}
onChange={(e) => setId(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="model">Model:</FormLabel>
<FormControl
type="text"
name="model"
value={Model || ""}
onChange={(e) => setModel(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="make">Make:</FormLabel>
<FormControl
type="text"
name="make"
value={Make || ""}
onChange={(e) => setMake(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="owner">Owner:</FormLabel>
<FormControl
type="text"
name="owner"
value={Owner || ""}
onChange={(e) => setOwner(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="registration">Registration:</FormLabel>
<FormControl
type="text"
name="registration"
value={Registration || ""}
onChange={(e) => setRegistration(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="address">Address:</FormLabel>
<FormControl
type="text"
name="address"
value={Address || ""}
onChange={(e) => setAddress(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="previousOwners">Previous Owners:</FormLabel>
<FormControl
type="text"
name="previousOwners"
value={previousOwners || ""}
onChange={(e) => setPreviousOwners(e.target.value)}
/>
</FormGroup>
<FormGroup>
<Button
type="button"
title="Add New Car"
onClick={(e) => create(e)}
>
<FontAwesomeIcon icon={faPlus} />
Add
</Button>
<Button
type="button"
title="Update a Car"
onClick={(e) => updateOne(e)}
>
<FontAwesomeIcon icon={faEdit} />
<span id="editone">x1</span> Update
</Button>
<Button
type="button"
title="Update Many Cars"
onClick={(e) => updateMany(e)}
>
<FontAwesomeIcon icon={faEdit} />
<span id="editmany">+</span> Update
</Button>
<Button
type="button"
title="Delete a Car"
onClick={(e) => remove(e)}
>
<FontAwesomeIcon icon={faTrashAlt} />
Delete
</Button>
</FormGroup>
</Form>
</Container>
</div>
);
};
// Exported CarEdit to App.js.
export default CarEdit;
// Requiring the schemas that has been created in the carsModel.js file.
const Car = require("../models/carsModel.js");
// Requiring Mongoose.
const mongoose = require("mongoose");
/**
* POST/ CREATE:
* @required Body properties: Model, Make, Owner, Registration, and the Address
* @param {*} req Creating a new post with the property.
* @param {*} res Updated copy of the content (copyContent).
* @returns List of cars and a confirmation message is returned to confirm that the post has been created or an error message should the
* request be unsuccessful.
*/
exports.createController = (req, res) => {
let car = new Car({
Model: req.body.Model,
Make: req.body.Make,
Owner: req.body.Owner,
Registration: req.body.Registration,
Address: req.body.Address,
previousOwners: req.body.previousOwners,
});
car
.save()
.then((cars) => res.json(cars))
.catch((err) => res.status(400).json("Error creating the car." + err));
};
/**
* GET/ READ:
* @required Content.
* @param {*} req Getting the array of cars.
* @param {*} res Copy of the content (copyContent).
* @returns A list of the current cars that are already written.
*/
// Requesting all the cars' information from MongoDB and retuning the response with the information.
exports.getAllController = (req, res) => {
Car.find()
.then((cars) => res.json(cars))
.catch((err) =>
res.status(400).json("Error getting the cars' information." + err)
);
};
// Requesting all the cars' information from MongoDB and retuning the response with the information.
exports.getOlderCars = (req, res) => {
Car.find({ Model: { $lt: 2016 } })
.then((cars) => res.json(cars))
.catch((err) =>
res.status(400).json("Error getting the cars' information." + err)
);
};
/**
* PUT/ UPDATE:
* @required Body properties: id.
* @param {*} req Post with the matching id to be returned and updated with the new post.
* @param {*} res Updated copy of the content (copyContent).
* @returns List of cars and a confirmation message is returned to confirm that the post has been updatedor an error message should the request
* be unsuccessful.
*/
// Fetching the information of one car by id for updating. Using $set to set the information for the relevant car with the matching id.
exports.updateOneController = (req, res) => {
Car.findOneAndUpdate(
req.params.id,
{
$set: {
Model: req.body.Model,
Make: req.body.Make,
Owner: req.body.Owner,
Registration: req.body.Registration,
Address: req.body.Address,
previousOwners: req.body.previousOwners,
},
},
{ new: true }
)
.then((cars) => res.json(cars))
.catch((err) => res.status(400).json("Error updating the car." + err));
};
// Allowing a user to update more than one car, using the model year of the car. Using $set to set the information for the relevant cars with
// the matching model years.
exports.updateManyController = (req, res) => {
Car.updateMany(
{
Model: req.params.Model,
},
{
$set: {
Make: req.body.Make,
Owner: req.body.Owner,
Registration: req.body.Registration,
Address: req.body.Address,
previousOwners: req.body.previousOwners,
},
}
)
.then((cars) => res.json(cars))
.catch((err) => res.status(400).json("Error updating the car." + err));
};
/**
* DELETE:
* @required Body properties: id.
* @param {*} req Post with the matching id to be deleted.
* @param {*} res Updated copy of the content (copyContent).
* @returns List of cars and a confirmation message is returned to confirm that the post has been deleted or an error message should the
* request be unsuccessful.
*/
// Fetching the information of one car by id for deletion.
exports.removeOneController = (req, res) => {
Car.findByIdAndRemove(req.params.id)
.then((cars) => res.json(cars))
.catch((err) => res.status(400).json({message: "Error deleting the car." + err}));
};
I have also pushed the complete application's code to GitHub: https://github.com/ChanBos/Car-Database-App
I would appreciate any assistance that anyone is willing to offer.
I have managed to find a solution for this after further research.
I have altered the code as follows:
- carsEdit.js
// Imported react libraries and hooks.
import React, { useState } from "react";
// Requiring Axios.
import axios from "axios";
// Imported components from React Bootstrap.
import {
Button,
Container,
Form,
FormGroup,
FormControl,
FormLabel,
} from "react-bootstrap";
// Imported icons from FontAwesome.
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faPlus, faEdit, faTrashAlt } from "@fortawesome/free-solid-svg-icons";
// Imported Swal from sweetalert2.
import Swal from "sweetalert2";
/**
* Set the initial states of the prop values using the useState() hook.
* @param {*} cars
* @param {*} setCars
*/
/**
* Used the useState() hook to set the initial values of the props.
* @returns The initial states of the prop values.
*/
const CarEdit = () => {
const [id, setId] = useState("");
const [Model, setModel] = useState("");
const [Make, setMake] = useState("");
const [Owner, setOwner] = useState("");
const [Registration, setRegistration] = useState("");
const [Address, setAddress] = useState("");
const [previousOwners, setPreviousOwners] = useState("");
/**
* Assigned an event.preventDefault() method to ensure that the page is not refreshed once the create function is executed.
* Fetching the content from http://localhost:8080/cars/create. Utilizing the Post method.
* Added the necessary props to alocate values to be written to the database.
* If successful a modal (Sweetalert2 - Swal.fire) will appear to confirm success and the content will be added to the UI as objects.
* If unsuccessful a modal (Sweetalert2 - Swal.fire) will appear displaying an error.
* @param {*} e Posting content to the database and returning the content as objects to the UI.
*/
const create = (e) => {
e.preventDefault();
axios
.post("cars/create", {
Model,
Make,
Owner,
Registration,
Address,
previousOwners,
})
.then((response) => {
Swal.fire({
imageUrl: "./images/success.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Success",
confirmButtonColor: "#007aff",
width: 400,
title: "SUCCESS!",
text: response.data.message,
}).then(function () {
window.location.reload();
});
})
.catch((error) => {
Swal.fire({
imageUrl: "./images/exclamation.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
text: error,
}).then(function () {
window.location.reload();
});
});
};
/**
* Assigned an event.preventDefault() method to ensure that the page is not refreshed once the update function is executed.
* Fetching the content from http://localhost:8080/cars/updateOne/:id. Utilizing the Put method.
* Added the necessary props to alocate values to be written to the database.
* If successful a modal (Sweetalert2 - Swal.fire) will appear to confirm success and the content will be added to the UI as objects.
* If unsuccessful a modal (Sweetalert2 - Swal.fire) will appear displaying an error.
* @param {*} e Updating content of one car, that exists in the database, and returning the content as objects to the UI via the modal year.
*/
const updateOne = (e) => {
e.preventDefault();
axios
.put(`cars/updateOne/${id}`, {
Model: Model,
Make: Make,
Owner: Owner,
Registration: Registration,
Address: Address,
previousOwners: previousOwners,
})
.then((response) => {
Swal.fire({
imageUrl: "./images/success.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Success",
confirmButtonColor: "#007aff",
width: 400,
title: "SUCCESS!",
text: response.data.message,
}).then(function () {
window.location.reload();
});
})
.catch((error) => {
Swal.fire({
imageUrl: "./images/exclamation.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
text: error.response.data.message,
}).then(function () {
window.location.reload();
});
});
};
/**
* Assigned an event.preventDefault() method to ensure that the page is not refreshed once the update function is executed.
* Fetching the content from http://localhost:8080/cars/updateMany/:id. Utilizing the Put method.
* Added the necessary props to alocate values to be written to the database.
* If successful a modal (Sweetalert2 - Swal.fire) will appear to confirm success and the content will be added to the UI as objects.
* If unsuccessful a modal (Sweetalert2 - Swal.fire) will appear displaying an error.
* @param {*} e Updating content of one car, that exists in the database, and returning the content as objects to the UI via the model year.
*/
const updateMany = (e) => {
e.preventDefault();
axios
.put(`cars/updateMany/${Model}`, {
Make: Make,
Owner: Owner,
Registration: Registration,
Address: Address,
previousOwners: previousOwners,
})
.then((response) => {
Swal.fire({
imageUrl: "./images/success.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Success",
confirmButtonColor: "#007aff",
width: 400,
title: "SUCCESS!",
text: response.data.message,
}).then(function () {
window.location.reload();
});
})
.catch((error) => {
Swal.fire({
imageUrl: "./images/exclamation.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
text: error.response.data.message,
}).then(function () {
window.location.reload();
});
});
};
/**
* Assigned an event.preventDefault() method to ensure that the page is not refreshed once the delete function is executed.
* Fetching the content from http://localhost:8080/cars/delete/:id. Utilizing the Delete method.
* Added the necessary props to remove values from the database.
* If successful a modal (Sweetalert2 - Swal.fire) will appear to confirm success and the content will be added to the UI as objects.
* If unsuccessful a modal (Sweetalert2 - Swal.fire) will appear displaying an error.
* @param {*} e Deleting content that exists in the database via id.
*/
const remove = (e) => {
e.preventDefault();
axios
.delete(`cars/delete/${id}`)
.then((response) => {
Swal.fire({
imageUrl: "./images/success.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Success",
confirmButtonColor: "#007aff",
width: 400,
title: "SUCCESS!",
text: response.data.message,
}).then(function () {
window.location.reload();
});
})
.catch((error) => {
Swal.fire({
imageUrl: "./images/exclamation.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
text: error.response.data.message,
}).then(function () {
window.location.reload();
});
});
};
/**
* Added the props to be set when the onChange() event is triggered to set the new values of the props when values are entered into the input
* elements.
* Created buttons for the cars app. Passed onClick() events to create, update and delete cars.
* @returns Form with labels, input and button elements that can be used to add, update one or many cars and delete cars.
*/
return (
<div>
<Container>
<Form className="d-flex flex-column">
<FormGroup>
<FormLabel htmlFor="id">ID:</FormLabel>
<FormControl
type="text"
name="id"
value={id}
onChange={(e) => setId(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="model">Model:</FormLabel>
<FormControl
type="text"
name="model"
value={Model || ""}
onChange={(e) => setModel(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="make">Make:</FormLabel>
<FormControl
type="text"
name="make"
value={Make || ""}
onChange={(e) => setMake(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="owner">Owner:</FormLabel>
<FormControl
type="text"
name="owner"
value={Owner || ""}
onChange={(e) => setOwner(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="registration">Registration:</FormLabel>
<FormControl
type="text"
name="registration"
value={Registration || ""}
onChange={(e) => setRegistration(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="address">Address:</FormLabel>
<FormControl
type="text"
name="address"
value={Address || ""}
onChange={(e) => setAddress(e.target.value)}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="previousOwners">Previous Owners:</FormLabel>
<FormControl
type="text"
name="previousOwners"
value={previousOwners || ""}
onChange={(e) => setPreviousOwners(e.target.value)}
/>
</FormGroup>
<FormGroup>
<Button
type="button"
title="Add New Car"
onClick={(e) => create(e)}
>
<FontAwesomeIcon icon={faPlus} />
Add
</Button>
<Button
type="button"
title="Update a Car"
onClick={(e) => updateOne(e)}
>
<FontAwesomeIcon icon={faEdit} />
<span id="editone">x1</span> Update
</Button>
<Button
type="button"
title="Update Many Cars"
onClick={(e) => updateMany(e)}
>
<FontAwesomeIcon icon={faEdit} />
<span id="editmany">+</span> Update
</Button>
<Button
type="button"
title="Delete a Car"
onClick={(e) => remove(e)}
>
<FontAwesomeIcon icon={faTrashAlt} />
Delete
</Button>
</FormGroup>
</Form>
</Container>
</div>
);
};
// Exported CarEdit to App.js.
export default CarEdit;
- carsController.js
// Requiring the schemas that has been created in the carsModel.js file.
const Car = require("../models/carsModel.js");
// Requiring Mongoose.
const mongoose = require("mongoose");
/**
* POST/ CREATE:
* @required Body properties: Model, Make, Owner, Registration, and the Address
* @param {*} req Creating a new post with the property.
* @param {*} res Updated copy of the content (copyContent).
* @returns List of cars and a confirmation message is returned to confirm that the post has been created or an error message should the
* request be unsuccessful.
*/
exports.createController = (req, res) => {
let car = new Car({
Model: req.body.Model,
Make: req.body.Make,
Owner: req.body.Owner,
Registration: req.body.Registration,
Address: req.body.Address,
previousOwners: req.body.previousOwners,
});
car
.save()
.then((cars) => res.json({ message: "Car created successfully.", cars }))
.catch((err) => res.status(400).json("Error creating the car.", err));
};
/**
* GET/ READ:
* @required Content.
* @param {*} req Getting the array of cars.
* @param {*} res Copy of the content (copyContent).
* @returns A list of the current cars that are already written.
*/
// Requesting all the cars' information from MongoDB and retuning the response with the information.
exports.getAllController = (req, res) => {
Car.find()
.then((cars) => res.json(cars))
.catch((err) =>
res.status(400).json("Error getting the cars' information.", err)
);
};
// Requesting all the cars' information from MongoDB and retuning the response with the information.
exports.getOlderCars = (req, res) => {
Car.find({ Model: { $lt: 2016 } })
.then((cars) => res.json(cars))
.catch((err) =>
res.status(400).json("Error getting the cars' information.", err)
);
};
/**
* PUT/ UPDATE:
* @required Body properties: id.
* @param {*} req Post with the matching id to be returned and updated with the new post.
* @param {*} res Updated copy of the content (copyContent).
* @returns List of cars and a confirmation message is returned to confirm that the post has been updatedor an error message should the request
* be unsuccessful.
*/
// Fetching the information of one car by id for updating. Using $set to set the information for the relevant car with the matching id.
exports.updateOneController = (req, res) => {
Car.findOneAndUpdate(
req.params.id,
{
$set: {
Model: req.body.Model,
Make: req.body.Make,
Owner: req.body.Owner,
Registration: req.body.Registration,
Address: req.body.Address,
previousOwners: req.body.previousOwners,
},
},
{ new: true }
)
.then((cars) => res.json({ message: "Car updated successfully.", cars }))
.catch((err) => res.status(400).json("Error updating the car.", err));
};
// Allowing a user to update more than one car, using the model year of the car. Using $set to set the information for the relevant cars with
// the matching model years.
exports.updateManyController = (req, res) => {
Car.updateMany(
{
Model: req.params.Model,
},
{
$set: {
Make: req.body.Make,
Owner: req.body.Owner,
Registration: req.body.Registration,
Address: req.body.Address,
previousOwners: req.body.previousOwners,
},
}
)
.then((cars) => res.json({ message: "Cars updated successfully.", cars }))
.catch((err) => res.status(400).json("Error updating the car.", err));
};
/**
* DELETE:
* @required Body properties: id.
* @param {*} req Post with the matching id to be deleted.
* @param {*} res Updated copy of the content (copyContent).
* @returns List of cars and a confirmation message is returned to confirm that the post has been deleted or an error message should the
* request be unsuccessful.
*/
// Fetching the information of one car by id for deletion.
exports.removeOneController = (req, res) => {
Car.findByIdAndRemove(req.params.id)
.then((cars) => res.json({ message: "Car deleted successfully.", cars }))
.catch((err) =>
res.status(400).json({ message: "Error deleting the car.", err })
);
};
Instead of this, for instance:
const remove = (e) => {
e.preventDefault();
axios
.delete(`cars/delete/${id}`)
.then((response) => {
if (response.status === 200 && response.data === "Applied successfully")
Swal.fire({
imageUrl: "./images/success.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Success",
confirmButtonColor: "#007aff",
width: 400,
title: "SUCCESS!",
});
setCars(response.data);
})
.catch((error) => {
console.log(error);
Swal.fire({
imageUrl: "./images/exclamation.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
}).then(function () {
window.location.reload();
});
});
};
exports.removeOneController = (req, res) => {
Car.findByIdAndRemove(req.params.id)
.then((cars) => res.json(cars))
.catch((err) => res.status(400).json({message: "Error deleting the car." + err}));
};
...it is supposed to be:
const remove = (e) => {
e.preventDefault();
axios
.delete(`cars/delete/${id}`)
.then((response) => {
Swal.fire({
imageUrl: "./images/success.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Success",
confirmButtonColor: "#007aff",
width: 400,
title: "SUCCESS!",
text: response.data.message,
}).then(function () {
window.location.reload();
});
})
.catch((error) => {
Swal.fire({
imageUrl: "./images/exclamation.gif",
imageWidth: 150,
imageHeight: 150,
imageAlt: "Error",
confirmButtonColor: "#ff0000",
width: 400,
title: "ERROR!",
text: error.response.data.message,
}).then(function () {
window.location.reload();
});
});
};
exports.removeOneController = (req, res) => {
Car.findByIdAndRemove(req.params.id)
.then((cars) => res.json({ message: "Car deleted successfully.", cars }))
.catch((err) =>
res.status(400).json({ message: "Error deleting the car.", err })
);
};
The changes made was due to Axios handling some of the functionality that has been removed (initially utilized) by default.