Pocket Mong-o-Dex
The Fast Lane Manual
Section titled “The Fast Lane Manual”T.A. Watts
If we write raw MongoDB queries in this app, we’re walking home.
Syntax HUD
Section titled “Syntax HUD”| Syntax | Purpose | Example |
|---|---|---|
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() |
The Blueprint
Section titled “The Blueprint”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!"));Hazard Map
Section titled “Hazard Map”| Hazard | Fix |
|---|---|
| Pending Promise | Forgot await on our database call. |
| Connection Error | Check the .env file and IP Whitelist. |
| Empty Objects | Our Schema might not match our data fields. |
| Ugly URLs | Use Slugs (my-page) instead of IDs. |
Solo’s Pro-Notes
Section titled “Solo’s Pro-Notes”- 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)
awaitthem.
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”📘 Mongoose Fundamentals: Your ODM for MongoDB (PDF)
📘 Mongoose Cheatsheet Part 1 (PNG)