Skip to content

Pocket Mong-o-Dex

T.A. Watts

If we write raw MongoDB queries in this app, we’re walking home.

SyntaxPurposeExample
new mongoose.Schema({})Defines the structure.const s = new LinkSchema({ url: String })
mongoose.model()Creates the Factory.const Link = mongoose.model('Link', s)
Model.find({})Returns an Array.await Project.find({ active: true })
Model.findOne({})Returns an Object.await Project.findOne({ slug: 'abc' })
Model.findById(id)Searches by _id.await Project.findById('65c...')
new Model(data).save()Writes to DB.const p = new Project(data); await p.save()

Dependencies: npm install express mongoose ejs dotenv

Server Connection:

mongoose.connect(process.env.MONGO_URI);
const db = mongoose.connection;
db.on("error", console.error);
db.once("open", () => console.log("Connected!"));

HazardFix
Pending PromiseForgot await on our database call.
Connection ErrorCheck the .env file and IP Whitelist.
Empty ObjectsOur Schema might not match our data fields.
Ugly URLsUse Slugs (my-page) instead of IDs.

  • Schema vs. Model: The Schema is the floor plan. The Model is the house factory. We can’t live in a floor plan.
  • Queries: Mongoose queries return a Query Object, not a standard Promise, but they behave like Promises so we can (and must) await them.

📘 Mongoose Fundamentals: Your ODM for MongoDB (PDF)

📘 Mongoose Cheatsheet Part 1 (PNG)