1. Home
  2. Explore
  3. Computer Science
  4. Node.js Express API

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Node.js Express API

  • 26Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Technology Stack

What is the primary purpose of Node.js in the context of building a web API?

26 questions

  1. 1

    What is the primary purpose of Node.js in the context of building a web API?

    Model answer

    Node.js allows JavaScript to run on the server, serving as the server-side runtime environment for building the web API.

    Explanation

    Node.js utilizes the same JavaScript engine (V8) as Google Chrome, enabling developers to use JavaScript for both front-end and back-end development. Its non-blocking I/O model makes it efficient for building scalable network applications like RESTful APIs.

  2. 2

    Which web framework is used with Node.js to handle requests and provide web server functionality for the API?

    Model answer

    Express.js is the web framework used with Node.js to handle HTTP requests and manage the web server for the API.

    Explanation

    Express.js simplifies the process of building web applications and APIs in Node.js by providing a robust set of features for routing, middleware, and template engine integration. It abstracts away much of the low-level HTTP handling.

  3. 3

    What database technology is chosen as the data store for the bookstore API?

    Model answer

    MongoDB is chosen as the NoSQL database for storing the book and genre data in the API.

    Explanation

    MongoDB is a document-oriented database that stores data in flexible, JSON-like documents. This schema-less nature makes it suitable for rapidly developing applications and handling evolving data structures, which is beneficial for a bookstore application where book details might vary.

  4. 4

    What is Mongoose.js, and how is it utilized in this Node.js Express API?

    Model answer

    Mongoose.js is an Object Data Modeling (ODM) library for MongoDB and Node.js, used to define schemas for data models (like books and genres) and to interact with the MongoDB database programmatically.

    Explanation

    Mongoose provides a straightforward, schema-based solution to model application data. It includes features like schema validation, middleware, and query builders, making interactions with MongoDB more structured and robust than using the native MongoDB driver directly.

  5. 5

    Why is the API built from scratch without using generators or scaffolding tools?

    Model answer

    Building from scratch is preferred for learning purposes, as it exposes the underlying processes and configurations that are often hidden when using generators or scaffolding, thereby providing a deeper understanding.

    Explanation

    While generators and scaffolding tools can speed up development for experienced users, they obscure the fundamental setup and configuration details. For newcomers, a from-scratch approach ensures that every file, folder, and line of code is explicitly understood, fostering better learning.

  6. 6

    What are the four primary types of HTTP requests that the RESTful API will handle for data manipulation?

    Model answer

    The API will handle GET requests to retrieve data, POST requests to add new data, PUT requests to update existing data, and DELETE requests to remove data.

    Explanation

    These four request types (GET, POST, PUT, DELETE) correspond to the fundamental CRUD (Create, Read, Update, Delete) operations in a RESTful API. GET is for reading, POST for creating, PUT for updating, and DELETE for deleting resources.

  7. 7

    What is the initial file and folder structure created for the Node.js Express application?

    Model answer

    Initially, an app.js file (the main gateway) and a models folder are created within the project directory.

    Explanation

    The app.js file serves as the entry point for the Express application, containing the main server logic and route definitions. The models folder is intended to house Mongoose schemas and functions for interacting with specific database collections (e.g., books, genres), promoting modularity and organization.

  8. 8

    How is the package.json file created for the project, and what is its significance?

    Model answer

    The package.json file is created using npm init, and it is significant because it stores project metadata and lists all the dependencies (Node.js modules) required for the application.

    Explanation

    Running npm init interactively prompts for project details, generating the package.json file. This file is crucial for managing project dependencies, defining scripts, and providing information about the package, allowing other developers to easily set up and run the project by simply running npm install to get all listed dependencies.

  9. 9

    Which three main Node.js modules are listed as dependencies in package.json for this project?

    Model answer

    The three main Node.js modules listed as dependencies are Express, body-parser, and Mongoose.

    Explanation

    Express provides the web framework, body-parser is middleware for parsing incoming request bodies (essential for POST/PUT requests), and Mongoose is the ODM for MongoDB interaction. These are core components for building the API.

  10. 10

    How are the project dependencies installed after defining them in package.json?

    Model answer

    After defining dependencies in package.json, they are installed locally by running the npm install command in the project directory.

    Explanation

    The npm install command reads the dependencies section of package.json and downloads all specified modules into the node_modules folder within the project. This ensures that the project has all its necessary libraries available.

  11. 11

    What is the command to run the Node.js application, and how can nodemon improve the development workflow?

    Model answer

    The command to run the application is node app.js. nodemon improves the workflow by automatically restarting the server whenever file changes are detected, eliminating the need for manual restarts.

    Explanation

    Manually stopping and starting the server (Ctrl+C then node app.js) after every code change is tedious. nodemon (npm install -g nodemon to install globally) watches for file changes and reloads the application automatically, significantly speeding up the development cycle.

  12. 12

    What is the default URI for the main landing page of the API, and what message is displayed there?

    Model answer

    The default URI for the main landing page is / (localhost:3000), and it displays a message instructing users to "Please use /API/books or /API/genres" to access the API endpoints.

    Explanation

    This setup differentiates the root endpoint from the actual API endpoints. The root serves as a simple guide for users, directing them to the structured API routes rather than serving application content directly.

  13. 13

    How is the connection to the MongoDB database established in the app.js file?

    Model answer

    The connection to MongoDB is established using mongoose.connect('mongodb://localhost/bookstore'), specifying the database URI.

    Explanation

    This line of code initiates the connection to the MongoDB instance running on the local machine, targeting a database named 'bookstore'. If the 'bookstore' database does not exist, MongoDB will create it automatically upon the first data insertion.

  14. 14

    What is the purpose of res.json() in an Express route handler?

    Model answer

    res.json() is used to send a JSON response to the client, automatically setting the Content-Type header to application/json.

    Explanation

    In RESTful APIs, data is typically exchanged in JSON format. res.json() is a convenient Express method that takes a JavaScript object or array and converts it into a JSON string, sending it back to the client as the response body.

  15. 15

    Explain the role of a Mongoose Schema in the genre.js model file.

    Model answer

    A Mongoose Schema (genreSchema) defines the structure and data types for documents within a MongoDB collection (e.g., 'genres') and can include validation rules like required: true.

    Explanation

    While MongoDB itself is schema-less, Mongoose Schemas impose a structure at the application level. This ensures data consistency, allows for built-in validation (e.g., name being a required string), and provides a blueprint for how documents of a particular type should look.

  16. 16

    How is the create_date field automatically populated in the genreSchema?

    Model answer

    The create_date field is automatically populated by setting its type to Date and its default value to Date.now in the Mongoose Schema.

    Explanation

    By using default: Date.now, Mongoose will automatically assign the current date and time to the create_date field whenever a new genre document is created, without requiring explicit input from the client.

  17. 17

    How is the genre model made accessible to other parts of the Node.js application?

    Model answer

    The genre model is made accessible using module.exports = mongoose.model('Genre', genreSchema); in the genre.js file, allowing it to be require()d.

    Explanation

    In Node.js, module.exports specifies what a module exposes to other modules. By assigning the Mongoose model to module.exports, other files (like app.js) can import and use the Genre model for database operations by simply calling require('./models/genre').

  18. 18

    Describe the purpose of the getGenres function in the genre.js model.

    Model answer

    The getGenres function is a model method designed to retrieve all genre documents from the MongoDB database, optionally limiting the number of results.

    Explanation

    This function encapsulates the database query logic (Genre.find()) for fetching genres. It promotes separation of concerns by keeping database operations within the model file, making the route handlers cleaner and focused on request/response handling.

  19. 19

    How does app.get('/api/genres', ...) utilize the getGenres function from the genre model?

    Model answer

    The app.get('/api/genres', ...) route handler calls Genre.getGenres() and passes a callback function that handles either an error or the retrieved genre data, which is then sent as a JSON response.

    Explanation

    This illustrates the interaction between the route and the model. The route defines the endpoint, and when accessed, it delegates the data retrieval task to the getGenres function in the model. The callback ensures that the response is sent only after the database operation completes.

  20. 20

    What is the URI pattern for retrieving a single book, and how is the book ID extracted from the request?

    Model answer

    The URI pattern is /api/books/:_id. The book ID is extracted from the request using req.params._id, where _id matches the parameter name in the URI pattern.

    Explanation

    Express uses colon (:) in route paths to define dynamic segments, which become properties of the req.params object. So, for /api/books/123, req.params._id would be '123'. This allows for flexible routing to fetch specific resources.

  21. 21

    What is the role of body-parser middleware in handling POST requests?

    Model answer

    body-parser middleware, specifically app.use(bodyParser.json()), parses incoming JSON request bodies, making them accessible via req.body in route handlers.

    Explanation

    When a client sends data (e.g., a new genre or book) in the body of a POST or PUT request, it's typically in JSON format. body-parser intercepts this raw data, parses it, and populates req.body with the resulting JavaScript object, simplifying data access for the application.

  22. 22

    How is a new genre added to the database using the API, and what HTTP method is used?

    Model answer

    A new genre is added via a POST request to /api/genres. The request body contains the genre data (e.g., {"name": "Romance"}), which is then processed by Genre.create() in the model.

    Explanation

    The app.post('/api/genres', ...) route handler extracts the genre data from req.body, then calls the addGenre function (which internally uses Genre.create(genreObj)). This creates a new document in the genres collection in MongoDB.

  23. 23

    When updating a genre, what are the three main parameters passed to the updateGenre function in the model?

    Model answer

    The updateGenre function receives the _id of the genre to update, the genre object containing the new data, and an options object for Mongoose query options.

    Explanation

    The _id identifies the specific document to modify. The genre object (often derived from req.body) contains the fields to be updated. The options object can be used for things like new: true to return the updated document, though in this example, it's left blank.

  24. 24

    Why did updating a book with only a new title result in other fields becoming null or disappearing?

    Model answer

    When updating a book with only a new title, other fields became null because the update object in the Mongoose findOneAndUpdate method was explicitly assigning only the provided fields, effectively overwriting or removing others if not included.

    Explanation

    The update object in the model's updateBook function constructs a document with specific fields (title, genre, etc.). If a field is omitted from the incoming book object (from req.body), it gets set to null or its default in the database, because the entire update object is replacing or setting values for the specified fields, rather than merging them.

  25. 25

    What is the HTTP method and URI pattern used to delete a genre by its ID?

    Model answer

    The HTTP method is DELETE, and the URI pattern is /api/genres/:_id to delete a genre by its ID.

    Explanation

    The DELETE method is semantically used for removing resources. The :_id parameter in the URI allows the server to identify which specific genre document should be removed from the database.

  26. 26

    How is a genre actually removed from the MongoDB database in the deleteGenre model function?

    Model answer

    The deleteGenre function uses Genre.remove(query, callback) where query is _id: id to target and remove a specific genre document.

    Explanation

    The Genre.remove() Mongoose method is used to delete documents matching a given query. By constructing a query object that matches the _id passed to the function, only the specified genre document is deleted from the genres collection.

1 of 26
Question 1 of 26

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent