0
0
Expressframework~30 mins

Finding and querying documents in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Finding and Querying Documents with Express and MongoDB
📖 Scenario: You are building a simple Express server that connects to a MongoDB database. The database stores a collection of books with their titles and authors.You want to create routes to find and query these book documents.
🎯 Goal: Build an Express server with a MongoDB connection that can find all books and query books by author.
📋 What You'll Learn
Create a MongoDB collection named books with sample data
Set up an Express server with MongoDB connection
Create a route to find all books
Create a route to query books by author using a query parameter
💡 Why This Matters
🌍 Real World
Web servers often need to find and filter data from databases to show users relevant information.
💼 Career
Backend developers use Express and databases like MongoDB to build APIs that find and query documents efficiently.
Progress0 / 4 steps
1
Set up the books collection with sample data
Create a constant called books that is an array of objects with these exact entries: { title: 'The Hobbit', author: 'J.R.R. Tolkien' }, { title: '1984', author: 'George Orwell' }, and { title: 'To Kill a Mockingbird', author: 'Harper Lee' }.
Express
Need a hint?

Use const books = [ ... ] with the exact objects inside the array.

2
Set up Express server and MongoDB connection
Create a constant called express by requiring 'express'. Then create a constant called app by calling express(). Also create a constant called port and set it to 3000.
Express
Need a hint?

Use const express = require('express'), then const app = express(), and set const port = 3000.

3
Create route to find all books
Use app.get with the path '/books' and a callback with parameters req and res. Inside the callback, send the books array as JSON using res.json(books).
Express
Need a hint?

Use app.get('/books', (req, res) => { res.json(books); }) to send all books.

4
Create route to query books by author
Use app.get with the path '/books/search' and a callback with req and res. Inside, get the author query parameter from req.query.author. Filter the books array to only include books where book.author exactly matches the author query. Send the filtered array as JSON with res.json(filteredBooks). Finally, start the server listening on port with app.listen(port).
Express
Need a hint?

Use app.get('/books/search', (req, res) => { ... }), get author from req.query.author, filter books by exact author match, send filtered books with res.json, and start server with app.listen(port).