Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Practice: Mongoose Exercises on Relations and Performance

Practice Mongoose populate, aggregation, indexes and bulk operations with eight exercises - each has a runnable stand-in solution, the real Mongoose version and a challenge to extend.

Reading about populate, pipelines and indexes is one thing; choosing the right tool for a concrete question is the skill. This page gives eight exercises. For each, try to write the Mongoose code yourself first, then compare it with the real solution (read-only) and run the stand-in to see the data flow. Every runnable block can be edited, so change the data and predict the output before pressing Run.

The runnable code uses plain JavaScript over arrays because Mongoose and MongoDB cannot run on this site. Concepts come from References and populate() through Bulk writes and cursors.

Shared data

Exercises 1 to 4 use this data set: authors, posts and comments.

JavaScript
const authors = [
  { _id: 'a1', name: 'Ada', active: true },
  { _id: 'a2', name: 'Bob', active: true },
  { _id: 'a3', name: 'Cy', active: false },
];
const posts = [
  { _id: 'p1', title: 'Engines', author: 'a1', tags: ['math', 'history'], views: 120 },
  { _id: 'p2', title: 'Kernels', author: 'a2', tags: ['os'], views: 300 },
  { _id: 'p3', title: 'Notes', author: 'a1', tags: ['math'], views: 45 },
  { _id: 'p4', title: 'Ghost', author: 'a3', tags: [], views: 10 },
];

Exercise 1: Posts with author names

Task. List every post title with its author's name, using one extra query rather than one per post.

Real solution:

JavaScript
const rows = await Post.find().populate('author', 'name').lean();
Node.js Exercise 1: populate (stand-in)

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.

Exercise 2: Authors with their post counts

Task. Show each author with how many posts they have, without storing a counter.

Real solution (virtual populate with count):

JavaScript
authorSchema.virtual('postCount', { ref: 'Post', localField: '_id', foreignField: 'author', count: true });
const authors = await Author.find().populate('postCount');
Node.js Exercise 2: counting (stand-in)

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.

(Answer to the challenge: postSchema.index({ author: 1 }).)

Task. Return each tag with the number of posts and the total views, most views first.

Real solution:

JavaScript
await Post.aggregate([
  { $unwind: '$tags' },
  { $group: { _id: '$tags', posts: { $sum: 1 }, views: { $sum: '$views' } } },
  { $sort: { views: -1 } },
]);
Node.js Exercise 3: unwind and group (stand-in)

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.

Task. For each author, report the total views of their posts, but only for posts with at least 40 views, and show the author name (not the id).

Real solution:

JavaScript
await Post.aggregate([
  { $match: { views: { $gte: 40 } } },
  { $group: { _id: '$author', totalViews: { $sum: '$views' } } },
  { $lookup: { from: 'authors', localField: '_id', foreignField: '_id', as: 'a' } },
  { $unwind: '$a' },
  { $project: { _id: 0, name: '$a.name', totalViews: 1 } },
  { $sort: { totalViews: -1 } },
]);
Node.js Exercise 4: match, group, lookup (stand-in)

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.

(Group first so the join runs once per author, not once per post.)

Exercise 5: Choose the index

Task. A page shows the 20 newest open tickets for one team: find({ team, status: 'open' }).sort({ createdAt: -1 }).limit(20). Which compound index, and why?

Answer: { team: 1, status: 1, createdAt: -1 }: both equality fields first, then the sort field (the ESR rule from Compound, text and TTL indexes). Confirm with explain('executionStats'): expect IXSCAN and totalDocsExamined close to 20.

Node.js Exercise 5: why the sort needs no work (stand-in)

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.

Exercise 6: Safe import

Task. Import 5,000 products from a CSV where some rows are invalid. Insert all valid rows and report the invalid ones, without stopping at the first problem.

Real solution:

JavaScript
try {
  await Product.insertMany(rows, { ordered: false });
} catch (err) {
  console.log(err.insertedDocs?.length, 'inserted;', err.writeErrors?.length ?? 0, 'failed');
}
Node.js Exercise 6: unordered batch (stand-in)

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.

(Challenge answer: with ordered inserts the first error stops the batch, so A1 is inserted and everything from the invalid row on is skipped.)

Exercise 7: Transfer without overdraft

Task. Move money between two accounts so the balance never goes negative and an interrupted transfer leaves no half-finished state. Write the transaction and the conditional update (see Transactions and sessions).

Real solution sketch:

JavaScript
await session.withTransaction(async () => {
  const from = await Account.findOneAndUpdate({ _id: a, balance: { $gte: amt } }, { $inc: { balance: -amt } }, { session });
  if (!from) throw new Error('Insufficient funds');
  await Account.updateOne({ _id: b }, { $inc: { balance: amt } }, { session });
});
Node.js Exercise 7: guarded transfer (stand-in)

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.

Exercise 8: Review a design

Read this schema and list the problems, then compare with the notes below.

JavaScript
const userSchema = new Schema({
  email: String,
  followers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }],
  password: String,
});

Notes:

  • email is not required, unique or lowercase: duplicates and case variants will appear.
  • followers is unbounded; a popular account approaches the 16 MB limit. Store a Follow collection with (follower, followee) and a compound unique index.
  • posts duplicates information already on each post (author); use virtual populate instead of keeping two sides in sync.
  • password should be named passwordHash, hashed before saving and declared select: false.
  • No timestamps and no indexes for the queries the app will run.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which index best serves find({ team, status: 'open' }).sort({ createdAt: -1 })?

    Equality fields first, then the sort field (ESR), so the matching block is already in sort order.
  2. 2. Which option lets an import continue past invalid rows?

    Unordered inserts try every document and report all failures together.
  3. 3. Why group before $lookup in a report?

    Grouping reduces the number of documents entering the more expensive $lookup.
  4. 4. What is wrong with a followers array of ObjectIds on every user?

    Unbounded arrays hit the 16 MB limit and slow every write; model follows as their own collection.

Summary

  • Match the tool to the question: populate for display joins, aggregation for reports, indexes for speed.
  • Order compound indexes Equality, Sort, Range and verify with explain().
  • Use unordered bulk inserts for imports and conditional updates plus transactions for money.
  • Review schemas for unbounded arrays, missing constraints and sync problems.
  • Keep practicing by extending the projects in this chapter.

Next: Back to the Mongoose tutorial