Create read controller to get all quotes
const getQuotes = asyncHandler(async (req, res) => {
//Find quotes
res.status(200).json({ quotes });
res.status(200).json(quotes);
});
Create post controller to create a quote
const createQuote = asyncHandler(async (req, res) => {
if (!req.body) {
res.status(400);
throw new Error("Please add a quote and author field");
}
// Create quote
const quote = await Quote.create(req.body);
res.status(200).json(quote);
});
Create update controller to update a quote
const updateQuote = asyncHandler(async (req, res) => {
// Find the quote by Id
const quote = await Quote.findById(req.params.id);
if (!quote) {
res.status(400);
throw new Error("Quote not found");
}
// Update the quote
const updatedQuote = await Quote.findByIdAndUpdate(req.params.id, req.body, {
new: true,
});
res.status(200).json(updatedQuote);
});
Create update controller to delete a quote
const deleteQuote = asyncHandler(async (req, res) => {
// Find the quote by Id
const quote = await Quote.findById(req.params.id);
if (!quote) {
res.status(400);
throw new Error("Quote not found");
}
// Delete the quote
await quote.remove();
res
.status(200)
.json({ message: `Quote with the id ${req.params.id} deleted` });
});
N.B.: We won't be needing the update and delete routes in production. I decided to include the 2 so beginners can learn how to make a full CRUD (Create, Read, Update and Delete) API.