Finding and querying documents helps you get specific data from a database easily. It lets your app show or use only the information you need.
Finding and querying documents in Express
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Express
Model.find(query, projection, options, callback) // or using async/await const results = await Model.find(query, projection, options);
query is an object that specifies conditions to match documents.
projection (optional) selects which fields to return.
Examples
Express
User.find({ age: { $gte: 18 } })Express
Product.find({ category: 'books' }, 'title price')Express
Order.find({ status: 'shipped' }).limit(5)Sample Program
This Express app connects to a MongoDB database and defines a User model. It has a route '/adults' that finds all users aged 18 or older and returns their name and age as JSON.
Express
import express from 'express'; import mongoose from 'mongoose'; const app = express(); // Define a simple User schema const userSchema = new mongoose.Schema({ name: String, age: Number, role: String }); const User = mongoose.model('User', userSchema); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/testdb'); app.get('/adults', async (req, res) => { try { // Find users aged 18 or older const adults = await User.find({ age: { $gte: 18 } }, 'name age'); res.json(adults); } catch (error) { res.status(500).send('Error fetching users'); } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Important Notes
Always handle errors when querying the database to avoid crashes.
You can chain methods like .limit() or .sort() to control results.
Use projections to return only needed fields and improve performance.
Summary
Use Model.find() to get documents matching conditions.
Queries are objects describing what to search for.
Projections let you pick which fields to get back.
Practice
1. In Express with Mongoose, which method is used to find all documents matching a condition in a collection?
easy
Solution
Step 1: Understand the purpose of
This method retrieves documents from the database that match the given query conditions.Model.find()Step 2: Differentiate from other methods
Model.create()adds new documents,Model.update()modifies existing ones, andModel.delete()removes documents.Final Answer:
Model.find()-> Option DQuick 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
Solution
Step 1: Use an object to specify query conditions
The query must be an object with key-value pairs, like{ age: 30 }.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.Final Answer:
User.find({ age: 30 })-> Option AQuick 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
Solution
Step 1: Understand the query parameters
The first argument is the filter{ active: true }, so only active users are returned.Step 2: Understand the projection string
The second argument'name email'selects only these fields to be included in the returned documents.Final Answer:
An array of user objects with only 'name' and 'email' fields -> Option AQuick 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
Solution
Step 1: Check the projection argument
The projection should be an object with field names as strings or keys, like{ name: 1, price: 1 }.Step 2: Identify the syntax error
Using{ name, price }without values or quotes is invalid JavaScript object syntax here.Final Answer:
The projection object is missing quotes around field names -> Option CQuick 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
Solution
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.Step 2: Use correct projection syntax
Passing a string with space-separated field names like'_id total'is valid for projection in Mongoose.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.Final Answer:
Order.find({ status: 'shipped', total: { $gt: 50 } }, '_id total')-> Option BQuick 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
