Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 70 ยท Projects

Project: A Task Tracker Data Layer

Build the data layer of a task tracker: a document model, validation, CRUD functions, queries by status and due date, and indexes, on the practice engine.

In this project you build the part of an application that sits closest to the database: a data layer for a task tracker. It is the code that an HTTP API, a command-line tool or a mobile backend would call. You will decide what a task document looks like, validate it, write the create, read, update and delete functions, add the queries that real screens need (open tasks, tasks due this week, tasks by tag), and design the indexes that keep those queries fast as the data grows.

MongoDB cannot run on this site, so the project runs on a stand-in: plain JavaScript over an array of documents, with the same filter and update documents you would send to a real server. The index part is a simulation that counts how many documents a query has to look at, so you can see the effect of an index without a real query planner. Every filter and the index definitions are real MongoDB syntax and are also shown as read-only mongosh blocks. If you want a refresher on the engine, see The Practice Engine Used in This Tutorial.

The plan

Model Decide what a task looks like.
Validate Reject bad data at the door.
CRUD Create, list, update, delete.
Index Match indexes to queries.
1 / 2

Step 1: the document model

One task is one document. Everything about a task is read together on every screen, so there is nothing to gain by splitting it across collections: tags and subtasks are small and belong inside the task (Embedding vs Referencing explains the reasoning).

JavaScript
{
  _id: ObjectId("..."),
  title: "Write the lesson",
  status: "todo",                 // "todo" | "doing" | "done"
  priority: 2,                    // 1 = high, 2 = normal, 3 = low
  tags: ["writing", "mongodb"],
  due: ISODate("2026-11-12T00:00:00Z"),     // optional
  createdAt: ISODate("2026-11-06T09:00:00Z"),
  completedAt: ISODate("...")                // only when done
}

Some decisions here are worth stating. Dates are real Date values, not strings, so range queries and sorting work correctly (BSON Types). status is a small fixed set of values, which makes it easy to validate and to index. Optional fields (due, completedAt) are simply absent when they have no value; there is no need to store null. And createdAt is set by the data layer, never by the caller.

Step 2: validation and CRUD

Validation belongs in the data layer so that every caller gets it, whatever the interface. (A real deployment would also add a $jsonSchema validator in the database as a backstop; see Schema Validation.) The functions below implement a TaskStore with create, get, update, complete and remove. The update function only allows a whitelist of fields, which is also a defence against the operator-injection problem from NoSQL Injection and Safe Queries.

JS TaskStore: validation and CRUD

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

No output.

Notice the shape of the results. update returns matchedCount and modifiedCount like MongoDB, and a repeated update that changes nothing reports modifiedCount: 0. complete is idempotent: calling it twice does no harm, which is a good property for any operation that an API client may retry.

In a real driver, the same operations are one-liners. This is the real mongosh shape of the main functions:

JavaScript
db.tasks.insertOne({ title: "Write the lesson", status: "todo", priority: 2,
                     tags: ["writing"], createdAt: new Date() })

db.tasks.updateOne({ _id: id }, { $set: { status: "doing" } })

db.tasks.updateOne(
  { _id: id, status: { $ne: "done" } },                       // idempotent guard
  { $set: { status: "done", completedAt: new Date() } }
)

db.tasks.deleteOne({ _id: id })

The guard status: { $ne: "done" } in the filter makes complete atomic and idempotent on the server: a second call simply matches nothing.

Step 3: the queries the screens need

Work backwards from the screens. A task tracker typically needs:

  1. Open tasks, most urgent first: { status: { $in: ["todo", "doing"] } } sorted by due date, then priority.
  2. Due soon: tasks with due on or before some date, not yet done.
  3. By tag: { tags: "writing" }, which matches any element of the array (Querying Nested Fields and Arrays).
  4. Overdue count for a badge: countDocuments with due before now and status not done.
JavaScript
// open tasks, soonest first, then highest priority
db.tasks.find({ status: { $in: ["todo", "doing"] } }).sort({ due: 1, priority: 1 })

// due in the next 7 days
db.tasks.find({ status: { $ne: "done" }, due: { $lte: nextWeek } })

// overdue badge
db.tasks.countDocuments({ status: { $ne: "done" }, due: { $lt: new Date() } })

Tasks without a due field sort before dated ones in ascending order in real MongoDB (a missing field sorts as null, the lowest value), so decide whether your screen wants undated tasks first or last, and sort or filter accordingly. The stand-in below makes that choice explicit by putting undated tasks last.

Step 4: indexes

With a few hundred tasks, any query is fast. With millions (a multi-user product), a query without a supporting index must examine every document: a collection scan. Indexes fix that (How Indexes Work, Designing Compound Indexes). In a multi-user tracker every query also filters by owner, so the index design begins with ownerId. For this single-user project we focus on the two filters that matter, status and due.

The most useful real indexes for the queries above would be:

JavaScript
db.tasks.createIndex({ status: 1, due: 1 })     // open tasks and due-soon: equality, then range/sort
db.tasks.createIndex({ tags: 1 })               // multikey index: one entry per tag

The first follows the equality, sort, range idea: status is an equality or small $in match, and due is what we sort or range on. The second is a multikey index: MongoDB indexes each array element separately, so { tags: "writing" } can find tasks directly.

The simulation below does not implement a real B-tree; it implements the effect. createIndex builds a lookup from each indexed value to the matching documents, and find reports how many documents it had to examine with and without the index, which is what the explain() output calls docsExamined (explain() and the Profiler).

JS Queries by status, due date and tag, with an index

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

No output.

With 1,000 tasks, { status: "doing" } examines all 1,000 documents without an index and about 200 with one, and the tag query drops from 1,000 to 20. The ratio grows with the collection, which is the whole point: an index lets the work depend on the size of the answer, not on the size of the collection. The simulation also shows an honest limit: a low-selectivity field such as status (only three values) only helps so much, which is why the real index { status: 1, due: 1 } adds the date as a second key.

Always measure the real thing. On a real server, run db.tasks.find(...).explain("executionStats") and compare totalDocsExamined with nReturned. The simulation shows the idea; only a real explain shows what your data and your indexes actually do.

Step 5: wrap-up and extensions

You now have a complete, validated data layer: model, CRUD with idempotent completion, screen-driven queries and an index plan. Natural extensions to try on your own:

  • Add an ownerId to every task and put it first in each index, so each user's queries touch only their own data.
  • Add a subtasks array of small embedded documents and a function that ticks one off with an array update (Updating Arrays).
  • Use a TTL index to delete completed tasks after 30 days (Deleting Documents).
  • Store each completion as an event in a separate collection if you later want history.
  • Add pagination to the open-tasks list using the last seen (due, _id) pair rather than skip (Sorting, Limiting and Skipping).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the project make complete() idempotent?

    An idempotent operation gives the same result however many times it runs. That makes retries by clients and networks safe.
  2. 2. Why is tags stored as an array inside each task document instead of in a separate collection?

    Small data that is always read with its parent is a good candidate for embedding. A multikey index on tags makes searching by tag efficient.
  3. 3. What does an index let a query do?

    Without an index MongoDB scans the whole collection. With one it can jump to matching entries, so the work grows with the answer rather than with the collection.
  4. 4. Why does update() accept only a whitelist of field names?

    A whitelist stops callers from overwriting fields like createdAt or passing operator objects, which is a defence against injection and accidental damage.

Summary

  • Model a task as one document with embedded tags, real Date values, a small fixed set of statuses and optional fields simply absent.
  • Validate in the data layer so every caller gets the same rules, and whitelist the fields an update may change.
  • Make operations such as completion idempotent with a guard in the filter.
  • Derive queries from screens: open tasks, due soon, by tag, overdue counts.
  • Index for those queries: a compound { status, due } index and a multikey tags index; confirm with explain.
  • The index simulation shows the effect, while a real explain("executionStats") shows the truth.

Next, take on a project with more documents and relationships in Project: Blog with Comments and Tags.