Chuyển đến nội dung

Bài 11 · CRUD and Queries

Finding Documents in Mongoose

Read data with Mongoose: find, findOne, findById, countDocuments, exists, projections with select, sorting and what each method returns when nothing matches.

Reading data is where you will spend most of your time. Mongoose offers several finders; the right one depends on how many documents you expect and whether you know the _id. This lesson covers each finder, what it returns when nothing matches, and how to choose which fields come back.

The examples use a Product model with name, price, category and inStock fields, as in Creating documents.

The finders

Method Returns When nothing matches
Model.find(filter) Array of documents []
Model.findOne(filter) One document null
Model.findById(id) One document by _id null
Model.countDocuments(filter) A number 0
Model.exists(filter) { _id } or null null
Model.estimatedDocumentCount() A fast approximate total 0
Model.distinct(field, filter) Array of unique values []
JavaScript
const all = await Product.find();                         // everything
const cheap = await Product.find({ price: { $lt: 20 } }); // filtered
const one = await Product.findOne({ name: 'Mouse' });     // first match
const byId = await Product.findById('6733a1f2c0ffee0012345678');
const total = await Product.countDocuments({ inStock: true });
const has = await Product.exists({ sku: 'KB-100' });      // cheap existence check
const categories = await Product.distinct('category');

Two details are worth knowing. First, find() never returns null for an empty result; it returns an empty array. findOne() and findById() return null, so always check before using the result:

JavaScript
const product = await Product.findById(id);
if (!product) {
  return res.status(404).json({ message: 'Not found' });
}

Second, findById(id) is shorthand for findOne({ _id: id }). An invalid id string such as 'abc' produces a CastError (rejected promise), not null. Check with mongoose.isValidObjectId(id) when ids come from the URL.

Filters

A filter is an object of field/value pairs that must all match:

JavaScript
await Product.find({ category: 'peripherals', inStock: true });

That is an implicit AND. Operators like $gt, $in and $or are covered in the next lesson. Nested fields use dot notation: { 'address.city': 'London' }. An empty filter {} or none at all matches everything.

Mongoose casts filter values to the schema type, so { price: '19.5' } works as the number 19.5 and { _id: '6733...' } becomes an ObjectId.

Choosing fields with select

By default a query returns every field. Use a projection to return fewer, which reduces network traffic and memory:

JavaScript
await Product.find().select('name price');       // include only these (plus _id)
await Product.find().select('-tags -__v');       // exclude these
await Product.find().select({ name: 1, price: 1, _id: 0 }); // object form, drop _id
await Product.find({}, 'name price');            // second argument of find

You can include or exclude fields, but not mix the two (the only exception is _id, which you can exclude while including others). A field defined with select: false in the schema, such as a password hash, is left out unless you ask for it with .select('+password').

Sorting and counting results

JavaScript
await Product.find().sort({ price: 1 });         // ascending
await Product.find().sort('-price name');        // descending price, then name
await Product.find().sort({ price: -1 }).limit(3);

Sorting can use an index; without a suitable one MongoDB sorts in memory and fails on very large unindexed sorts. Pagination and lean queries goes deeper.

A stand-in find

The runnable example implements simplified find, findOne, findById, select and sort over an in-memory array. It is not Mongoose, but it makes the "returns an array, null, or []" rules concrete.

Node.js find, findOne, select and sort (stand-in, not Mongoose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Counting and existence

Use countDocuments(filter) for an exact count and estimatedDocumentCount() for a fast total with no filter (it reads collection metadata). To ask "is there any?", exists() is cheaper than loading the document, because it fetches only the _id:

JavaScript
if (await User.exists({ email })) {
  throw new Error('Email already registered');
}

As noted before, that check is not a replacement for a unique index, but it is good for friendly messages.

Iterating without loading everything

find() loads every match into memory. For big result sets use a cursor, which streams documents one at a time:

JavaScript
for await (const product of Product.find().cursor()) {
  await process(product);
}

The cursor keeps memory flat even for millions of documents.

Reading a document's fields

Documents expose fields as properties. For safety with missing values use optional chaining and defaults:

JavaScript
const city = customer.address?.city ?? 'unknown';

Use doc.get('address.city') for dot paths, and doc.toObject() if you need a detached copy.

Common mistakes

  • Treating find() like findOne(): const user = await User.find({ email }) gives an array, so user.name is undefined.
  • Not checking null before using the result of findOne().
  • Passing an invalid id string and being surprised by a CastError.
  • Loading full documents when you only need two fields. Use select.
  • Mixing inclusion and exclusion in one projection.
  • Loading a huge collection with find() instead of using a cursor or pagination.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does Model.find({ name: 'nobody' }) return when nothing matches?

    find always returns an array. Only findOne and findById return null for no match.
  2. 2. What does findById('abc') do when 'abc' is not a valid ObjectId?

    Casting the id fails, so the promise rejects. Use mongoose.isValidObjectId to check first.
  3. 3. Which call returns only the name and price of each product?

    select builds a projection that includes the listed fields (and _id).
  4. 4. Which method is cheapest for checking whether a matching document exists?

    exists fetches only the _id of one match, or null.

Summary

  • find returns an array, findOne and findById return a document or null; counts and existence have their own methods.
  • Filters are objects, cast to schema types; unknown ids raise CastError.
  • select builds projections: include or exclude, not both; -field excludes.
  • sort orders results, cursor() streams large result sets.

Next: Query operators and chaining

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.