-
Notifications
You must be signed in to change notification settings - Fork 515
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Project-Mongo-API - Elina Eriksson Hult #509
base: master
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Well done, just remember to use query params for filtering in the future!
// Route to fetch book by author | ||
app.get("/books/authors/:author", async (req, res) => { | ||
const { author } = req.params; | ||
try { | ||
// Use a case-insensitive regex to match authors | ||
const books = await Book.find({ authors: new RegExp(author, "i") }); | ||
|
||
if (books.length === 0) { | ||
return res.status(404).send("No books found for this author"); // Handle no results | ||
} | ||
res.json(books); // Send list of books by the author | ||
} catch(error) { | ||
console.error("Error retrieving books by author", error); // Log error | ||
res.status(500).send("Server error"); // Handle server errors | ||
} | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remember that even though you're filtering on an author, you're still returning books. So it would be more RESTful to make this a query param under the /books endpoint. Remember for future!
https://project-mongo-api-elina.onrender.com