Searching Data (Query)
Firestore queries let you read documents that match a condition. For example, you can use a query to read only the logged-in user's notes, show only pinned notes, or sort them newest first.
Code Example
javascript
import { getFirestore, collection, query, where, orderBy, limit, getDocs } from 'firebase/firestore';
const db = getFirestore();
async function getPinnedNotes(userId) {
const q = query(
collection(db, 'notes'),
where('ownerId', '==', userId),
where('isPinned', '==', true),
orderBy('createdAt', 'desc'),
limit(10)
);
const snapshot = await getDocs(q);
return snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data()
}));
}What does this code do?
where filters by condition, orderBy sorts the results, and limit caps the number of results, which helps performance.
You might need an index
Queries with multiple conditions plus sorting often need a Firestore index. The console error usually gives you a link to create that index — you can just build it from that link.