Skip to content
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

Arnau's MongoDB API #485

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
# Project Mongo API

Replace this readme with your own information about your project.

Start by briefly describing the assignment in a sentence or two. Keep it short and to the point.
This weeks project was about implementing an API server using mongoose to get data for a database hosted in MongoDB.

## The problem

Describe how you approached to problem, and what tools and techniques you used to solve it. How did you plan? What technologies did you use? If you had more time, what would be next?
The main problem about this and last week was about getting familiar with this new backend constelation of new information, try to grasp and understand this new context and vocabulary.

## View it live

Every project should be deployed somewhere. Be sure to include the link to the deployed project so that the viewer can click around and see what it's all about.
[here](https://arnaus-mongoab-api.onrender.com)
Empty file added middleware/Middleware.js
Empty file.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"@babel/preset-env": "^7.16.11",
"cors": "^2.8.5",
"express": "^4.17.3",
"mongoose": "^8.0.0",
"express-list-endpoints": "^7.1.0",
"mongoose": "^8.3.4",
"nodemon": "^3.0.1"
}
}
126 changes: 113 additions & 13 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,132 @@
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
import mongoose from "mongoose";
import expressListEndpoints from "express-list-endpoints";

// If you're using one of our datasets, uncomment the appropriate import below
// to get started!
// import avocadoSalesData from "./data/avocado-sales.json";
// import booksData from "./data/books.json";
// import goldenGlobesData from "./data/golden-globes.json";
// import netflixData from "./data/netflix-titles.json";
// import topMusicData from "./data/top-music.json";

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl);
//This will connect us to the Data Base
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/books";
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey! did you know that with new Mongoose version you could just write mongoose.connect(mongoUrl)? 👍

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No i didn't, thank's! I feel like I have to improve the documentation part, I'm still green on looking for it.

mongoose.Promise = Promise;

//Here we create a Book modell
const Book = mongoose.model("Book", {
bookID: Number,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove bookId from the Schema: Mongoose automatically assigns a unique _id field to each document, so you don't need to define the field in your schema, you can even remove it from the data object

title: String,
authors: String,
average_rating: Number,
isbn: Number,
isbn13: Number,
language_code: String,
num_pages: Number,
ratings_count: Number,
text_reviews_count: Number,
});

// Defines the port the app will run on. Defaults to 8080, but can be overridden
// when starting the server. Example command to overwrite PORT env variable value:
// PORT=9000 npm start
// PORT=8080 npm start
const port = process.env.PORT || 8080;
const app = express();

// Add middlewares to enable cors and json body parsing
app.use(cors());
app.use(express.json());
app.use(bodyParser.json());

// Start defining your routes here
app.get("/", (req, res) => {
res.send("Hello Technigo!");
const endpoints = expressListEndpoints(app);
res.json(endpoints);
// res.send("<b>This is my first API Database using MongoDB!");
});

app.get("/books", async (req, res) => {
try {
const books = await Book.find();
res.json(books);
} catch (error) {
res.status(500).json({ error: "Internal server error" });
}
});

app.get("/books/:id", async (req, res) => {
const { id } = req.params;
try {
const book = await Book.findOne({ bookID: id });

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you're trying to find the _id value accessing it with bookID and that's why it's not working. It should look like:
const book = await Book.findOne({ _id: id });

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The datajson cames with a "bookID" and I got confused, nice you noticed, now it's working:)

if (book) {
res.json(book);
} else {
res.status(404).json({ error: "Book not found" });
}
} catch (error) {
res.status(500).json({ error: "Internal server error" });
}
});

/// example: books/search?title=Harry%20Potter&author=J.K.%20Rowling
/// example: books/search?title=Harry%20Potter
/// example: books/search?author=J.K.%20Rowling
app.get("/books/search", async (req, res) => {
const { title, author } = req.query;
try {
let query = {};
if (title) {
query.title = { $regex: title, $options: "i" };
}
if (author) {
query.authors = { $regex: author, $options: "i" };
}
const books = await Book.find(query);
res.json(books);
} catch (error) {
res.status(500).json({ error: "Internal server error" });
}
});

//example: /books/language/eng
app.get("/books/language/:language_code", async (req, res) => {
const { language_code } = req.params;
try {
const books = await Book.find({ language_code });
if (books.length > 0) {
res.json(books);
} else {
res
.status(404)
.json({ error: "No books found for the specified language code" });
}
} catch (error) {
res.status(500).json({ error: "Internal server error" });
}
});

//example /books/rating?min_rating=3.5&max_rating=4.5
app.get("/books/rating", async (req, res) => {
const { min_rating = 0, max_rating = 5 } = req.query;
try {
const books = await Book.find({
average_rating: {
$gte: parseFloat(min_rating),
$lte: parseFloat(max_rating),
},
});
if (books.length > 0) {
res.json(books);
} else {
res
.status(404)
.json({ error: "No books found within the specified rating range" });
}
} catch (error) {
res.status(500).json({ error: "Internal server error" });
}
});

//any other endpoints with GET method that are not acceptable -> 404 error
app.use((req, res, next) => {
const err = new Error(`Cannot find endpoint: ${req.originalUrl}.`);
err.statusCode = 404;
next(err);
});

// Start the server
Expand Down