Query
- Node.js course
- Advanced
- Lesson 28/83
- 5 min
Learn Mongoose queries and filtering.
What is a Query?
A Query in Mongoose is a database search operation. Model.find(condition) returns a Query object; it runs asynchronously and you await it.
Core query methods: find() (all matches), findOne() (first match), findById(id) (by ID). The filter is an object: { age: { $gt: 18 } } finds documents where age is greater than 18. Queries are chainable: User.find(filter).sort({ name: 1 }).limit(10).
find, findById, findOne
There are three core search methods. find(filter) returns all matching documents as an array. findOne(filter) returns the first matching document. findById(id) finds a single document by its unique ID.
All are asynchronous; you use them with await. An empty filter {} returns all documents. If no document matches, find returns an empty array [], while findOne and findById return null.
Practice Log the type of find
Import mongoose. Create a model with mongoose.model("User", { name: String }). Log typeof User.find.
Starter code
// import the module
// create a model
// log the type of findSample solution
const mongoose = require("mongoose");
const User = mongoose.model("User", { name: String });
console.log(typeof User.find);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does User.find() return?
- Bir dize
- A number
- Bir Buffer
- Bir Query nesnesi Correct answer
Explanation: User.find() returns a Query object.
2 Match each piece to its role
| Term | Meaning |
|---|---|
Model.find() |
Finds all docs |
Model.findById() |
Finds by ID |
Model.findOne() |
Finds one doc |
Query |
Query object |
3 Complete the method name
const results = await User.____({})
const results = await User.find({})
Explanation: User.find({}) finds all documents.