The MongoDB You Need for Node

MongoDB keeps data as documents, much like the JavaScript objects you already use. Learn documents and collections, how to shape a document (embed or reference), install MongoDB and Compass on your computer (or use a free Atlas cluster), and connect from Node with the official driver to save and read your first documents.

Updated

MongoDB in Plain Words

  1. Documents and Collections (Apprentice): MongoDB keeps an app's data as documents, records that look like JavaScript objects, grouped into collections inside a database, and every document carries its own unique _id.
  2. Shaping a Document: Embed or Reference (Journeyman): Related data either goes inside a document, embedded, when it is read with it, or lives in its own collection and is pointed to by its _id, referenced, when it is shared, changes on its own or grows without end.

Setting Up MongoDB

  1. Setup: MongoDB and Compass (Apprentice): Install MongoDB Community Server and Compass on Windows or macOS, check that the server is running, and connect Compass to it at mongodb://localhost:27017, or use a free Atlas cluster in the cloud instead.

The Official Driver

  1. Connecting from Node and Saving Documents (Apprentice): The official mongodb package connects Node to MongoDB with a MongoClient made from a connection string kept in .env, saves documents with insertOne and insertMany, reads them back with find().toArray(), and closes the client when the work is done.

Exercise: Plant Shop Catalog

  1. Exercise: Plant Shop Catalog (Apprentice): Move a plant shop's catalog into MongoDB with the official driver, connecting, saving 12 plants with insertMany, reading them back, finding the pet-safe ones and adding a new plant, and let tests on a throwaway MongoDB check every function.