Bird
Raised Fist0
Expressframework~10 mins

Finding and querying documents in Express - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Finding and querying documents
Start Express app
Receive HTTP GET request
Parse query parameters
Build query object
Call database find method
Database returns matching documents
Send documents as HTTP response
End request
The Express app receives a GET request, extracts query parameters, builds a query, fetches matching documents from the database, and sends them back as a response.
Execution Sample
Express
app.get('/users', async (req, res) => {
  const { age } = req.query;
  const users = await User.find({ age: Number(age) });
  res.json(users);
});
This code listens for GET requests on '/users', queries users by age, and returns matching users as JSON.
Execution Table
StepActionInput/ConditionDatabase QueryResultResponse Sent
1Receive GET requestGET /users?age=30N/AN/AN/A
2Parse query parametersage=30N/AN/AN/A
3Build query object{ age: 30 }N/AN/AN/A
4Call User.find(){ age: 30 }Find users with age 30[{name: 'Alice', age: 30}, {name: 'Bob', age: 30}]N/A
5Send responseN/AN/AN/AJSON array of users with age 30
6End requestN/AN/AN/AResponse complete
💡 Request ends after sending JSON response with matching documents.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
req.query.ageundefined'30''30''30''30'
queryObject{}{}{ age: 30 }{ age: 30 }{ age: 30 }
usersundefinedundefinedundefined[{name: 'Alice', age: 30}, {name: 'Bob', age: 30}][{name: 'Alice', age: 30}, {name: 'Bob', age: 30}]
Key Moments - 2 Insights
Why is the age value a string ('30') in the query object instead of a number?
Query parameters from the URL are always strings. To query by number, you must convert the string to a number before building the query object. See Step 3 in execution_table where age is still a string.
What happens if no documents match the query?
The database returns an empty array. The response will send an empty JSON array. This is shown in Step 4 where the result could be [].
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 4, what does the database return?
AA single user object
BAn empty object
CAn array of user objects with age 30
DAn error message
💡 Hint
Check the 'Result' column in Step 4 of execution_table
At which step is the query object created?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column in execution_table where the query object is built
If the URL query parameter was age=25, how would the 'users' variable change after Step 4?
AIt would contain users with age 25
BIt would contain users with age 30
CIt would be undefined
DIt would contain all users
💡 Hint
Refer to variable_tracker and execution_table Step 4 for how query affects users
Concept Snapshot
Express GET route listens for requests
Extract query parameters from req.query
Build a query object for database
Use Model.find(query) to get matching documents
Send results as JSON response
Query params are strings; convert if needed
Full Transcript
This example shows how an Express app handles finding and querying documents. When a GET request arrives at '/users' with a query parameter like age=30, the app extracts the age from req.query. It builds a query object with this age and calls User.find() to get matching users from the database. The database returns an array of user objects matching the age. Finally, the app sends this array as a JSON response. Note that query parameters are strings, so if you want to query by number, you should convert the string to a number before querying. If no users match, an empty array is returned and sent. This flow helps you understand how to find and query documents in Express apps.

Practice

(1/5)
1. In Express with Mongoose, which method is used to find all documents matching a condition in a collection?
easy
A. Model.delete()
B. Model.create()
C. Model.update()
D. Model.find()

Solution

  1. Step 1: Understand the purpose of Model.find()

    This method retrieves documents from the database that match the given query conditions.
  2. Step 2: Differentiate from other methods

    Model.create() adds new documents, Model.update() modifies existing ones, and Model.delete() removes documents.
  3. Final Answer:

    Model.find() -> Option D
  4. Quick Check:

    Find documents = Model.find() [OK]
Hint: Use find() to get matching documents [OK]
Common Mistakes:
  • Confusing find() with create()
  • Using update() to retrieve documents
  • Trying to delete documents to find them
2. Which of the following is the correct syntax to find all users with age 30 using Mongoose in Express?
easy
A. User.find({ age: 30 })
B. User.find(age == 30)
C. User.find('age: 30')
D. User.find({ 'age' = 30 })

Solution

  1. Step 1: Use an object to specify query conditions

    The query must be an object with key-value pairs, like { age: 30 }.
  2. Step 2: Check syntax correctness

    User.find({ age: 30 }) uses correct JavaScript object syntax. Options B, C, and D have syntax errors or wrong formats.
  3. Final Answer:

    User.find({ age: 30 }) -> Option A
  4. Quick Check:

    Query object syntax = User.find({ age: 30 }) [OK]
Hint: Use curly braces with key: value for queries [OK]
Common Mistakes:
  • Using comparison operators inside find()
  • Passing query as a string
  • Using assignment (=) instead of colon (:) in object
3. What will be the output of this code snippet in Express using Mongoose?
const users = await User.find({ active: true }, 'name email');
console.log(users);
medium
A. An array of user objects with only 'name' and 'email' fields
B. An array of user objects with all fields including 'active'
C. A single user object with 'name' and 'email' fields
D. An error because projection syntax is wrong

Solution

  1. Step 1: Understand the query parameters

    The first argument is the filter { active: true }, so only active users are returned.
  2. Step 2: Understand the projection string

    The second argument 'name email' selects only these fields to be included in the returned documents.
  3. Final Answer:

    An array of user objects with only 'name' and 'email' fields -> Option A
  4. Quick Check:

    Projection limits fields = An array of user objects with only 'name' and 'email' fields [OK]
Hint: Second argument in find() selects fields to return [OK]
Common Mistakes:
  • Expecting all fields to be returned
  • Thinking projection returns a single object
  • Using wrong projection syntax causing errors
4. Identify the error in this Mongoose query:
const results = await Product.find({ price: { $gt: 100 } }, { name, price });
medium
A. The find method cannot use async/await
B. The query operator $gt is invalid
C. The projection object is missing quotes around field names
D. The filter object should be a string

Solution

  1. Step 1: Check the projection argument

    The projection should be an object with field names as strings or keys, like { name: 1, price: 1 }.
  2. Step 2: Identify the syntax error

    Using { name, price } without values or quotes is invalid JavaScript object syntax here.
  3. Final Answer:

    The projection object is missing quotes around field names -> Option C
  4. Quick Check:

    Projection keys must be strings or key-value pairs [OK]
Hint: Projection keys need explicit values or quotes [OK]
Common Mistakes:
  • Using shorthand object keys without values in projection
  • Misunderstanding $gt operator
  • Thinking async/await is invalid with find()
5. You want to find all orders where the status is 'shipped' and the total is greater than 50, but only return the order ID and total fields. Which is the correct Mongoose query in Express?
hard
A. Order.find({ status: 'shipped', total: { $gt: 50 } }, { _id: 1, total: 1 })
B. Order.find({ status: 'shipped', total: { $gt: 50 } }, '_id total')
C. Order.find({ status: 'shipped', total: { $gt: 50 } }, { _id: true, total: true })
D. Order.find({ status: 'shipped' && total > 50 }, '_id total')

Solution

  1. Step 1: Write the correct filter object

    The filter must be { status: 'shipped', total: { $gt: 50 } } to find orders with status 'shipped' and total greater than 50.
  2. Step 2: Use correct projection syntax

    Passing a string with space-separated field names like '_id total' is valid for projection in Mongoose.
  3. Step 3: Evaluate options

    Order.find({ status: 'shipped', total: { $gt: 50 } }, { _id: 1, total: 1 }) uses an object projection with 1s which is valid but the question asks for the best correct query. Order.find({ status: 'shipped', total: { $gt: 50 } }, '_id total') uses string projection which is simpler and correct. Order.find({ status: 'shipped' && total > 50 }, '_id total') has invalid filter syntax. Order.find({ status: 'shipped', total: { $gt: 50 } }, { _id: true, total: true }) uses boolean true instead of 1 which is invalid in Mongoose projection.
  4. Final Answer:

    Order.find({ status: 'shipped', total: { $gt: 50 } }, '_id total') -> Option B
  5. Quick Check:

    Filter object + string projection = Order.find({ status: 'shipped', total: { $gt: 50 } }, '_id total') [OK]
Hint: Use object for filter, string for projection fields [OK]
Common Mistakes:
  • Using logical operators incorrectly in filter
  • Using boolean true instead of 1 in projection
  • Passing projection as object with invalid values