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.
0
0
Finding and querying documents in Express
Introduction
When you want to show a list of users with a certain role.
When you need to find a product by its name or ID.
When filtering blog posts by date or author.
When searching for orders with a specific status.
When retrieving all comments related to a post.
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
Finds all users who are 18 years old or older.
Express
User.find({ age: { $gte: 18 } })Finds all products in the 'books' category and returns only their title and price.
Express
Product.find({ category: 'books' }, 'title price')Finds the first 5 orders with status 'shipped'.
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'); });
OutputSuccess
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.