Loading Documents
The Retrieval Method
Section titled “The Retrieval Method”In mongosh, we used db.projects.find().
In Mongoose, we use the Model’s .find() method. Note that while many functions look identical to the shell, Mongoose adds extra features like automated validation.
SELECT FROM WHERE - Mongoose Style
Section titled “SELECT FROM WHERE - Mongoose Style”data/projects.js
We’ll add a helper class to manage our database operations. Here is the full content of data/projects.js:
const mongoose = require("mongoose");
// 1. The Blueprint: Define fields and typesconst projectSchema = new mongoose.Schema({ slug: { type: String, required: true, unique: true }, title: String, description: String, isActive: Boolean,});
// 2. The Model: The constructor used to interact with the collectionconst Project = mongoose.model("Project", projectSchema);
// 3. The Operations: Helper methodsclass ProjectOps { async getProjectList() { // Similar to mongosh: returns all documents matching the criteria return await Project.find({ isActive: true }); }}
module.exports = new ProjectOps();A Note on Architecture
Section titled “A Note on Architecture”We might notice we’re defining the Schema, creating the Model, and writing our database queries all in the same file (data/projects.js).
“Wait, isn’t that breaking MVC?”
Technically? Maybe a little. Pragmatically? It’s efficient. We aren’t building a monolith here. By keeping the data structure (Schema) next to the data operations (Queries), we avoid jumping between five different files just to change a variable name. It’s clean, organized, and keeps our “context switching” to a minimum.
Ensure we use await.
-
Database operations are asynchronous.
-
If we don’t await the promise, our view will render before the data arrives.
⏭ Next: Visualizing the Data
Section titled “⏭ Next: Visualizing the Data”We have the data.
Let’s list it out and link it up.