ORM Initialization
Relevant source files
The following files were used as context for generating this wiki page:The LostData application utilizes Mongoose as its Object-Document Mapper (ODM/ORM) to interact with a MongoDB database. The initialization process is a multi-step flow that involves setting up the database connection configuration, defining the data schema for models, and aggregating these components into a central db object. This object is then used throughout the application, primarily in server.js for establishing the database connection and in API routes for performing CRUD operations.
The core of the ORM initialization is handled within the APP/models/ directory, which acts as the data layer's foundation. It ensures that all database interactions are structured, validated, and consistent with the defined Model schema.
Database Configuration
The database connection string is managed in a dedicated configuration file. This file provides the URI needed by Mongoose to connect to the MongoDB instance.
Sources: APP/config/db.config.js
Configuration Parameters
The system prioritizes an environment variable MONGODB_URI for the connection string, providing a fallback to a local database for development purposes.
| Parameter | Description | Default Value |
|---|---|---|
url | The full MongoDB connection string URI. | mongodb://127.0.0.1:27017/model_db |
Sources: APP/config/db.config.js:2
Model Definition
The application defines a single Mongoose schema for "Models". This schema dictates the structure, data types, and validation rules for documents stored in the models collection.
Sources: APP/models/model.model.js
Model Schema
The schema includes fields for model identification, profile information, pricing, and content guidelines. It also includes an automated history tracking mechanism.
The diagram below illustrates the entity relationship for the Model schema.
Sources: APP/models/model.model.js:3-13
Schema Fields
| Field | Type | Constraints | Description |
|---|---|---|---|
id | String | required, unique | A unique identifier for the model. |
name | String | required | The name of the model. |
age | Number | - | The age of the model. |
location | String | - | The location of the model. |
profile | String | required | A detailed profile description. |
pricing | String | required | A string containing pricing information. |
dosAndDonts | String | required | A string outlining content do's and don'ts. |
extraTabs | Array | default: [] | An array for storing additional information tabs. |
history | Array | default: [] | An array that logs changes to the document. Automatically updated via a pre-save hook. |
Sources: APP/models/model.model.js:3-13
Pre-save Hook for History Tracking
A pre('save') middleware hook is attached to the schema. This hook automatically adds a history entry whenever an existing document is modified. The entry includes a timestamp, the action (update), and a list of modified fields.
// APP/models/model.model.js:18-25
schema.pre('save', function(next) {
if (this.isModified() && !this.isNew) {
this.history.push({
timestamp: new Date(),
action: 'update',
changes: this.modifiedPaths()
});
}
next();
});
Sources: APP/models/model.model.js:18-25
ORM Aggregation
The APP/models/index.js file serves as the central aggregator for the ORM setup. It combines the database configuration, the Mongoose library, and the model definitions into a single, exportable db object.
The following flowchart shows how index.js constructs the db object.
Sources: APP/models/index.js:1-9
This db object exposes three key properties:
db.mongoose: The imported Mongoose library instance.db.url: The connection string fromdb.config.js.db.models: The compiledModelcreated frommodel.model.js.
Sources: APP/models/index.js:6-8
Application Integration and Usage
The main server file and other scripts consume the db object to interact with the database.
Server Connection
On application startup, server.js imports the db object and uses its mongoose and url properties to establish a connection to the MongoDB database.
The sequence diagram below illustrates the connection process when the server starts.
Sources: server.js:25-26
Model Usage in API
The compiled Model is accessed via db.models and used directly in API route handlers to perform database operations like finding, creating, updating, and deleting documents.
// server.js:41, 44-49
const Model = db.models;
app.get("/api/models", async (req, res) => {
try {
const models = await Model.find({}).sort({ name: 1 });
res.json(models);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
Sources: server.js:41, server.js:44-49
Data Seeding
The seed.js script also utilizes the ORM initialization logic to populate the database with initial data. It imports the db object, connects to the database, and uses the Model.insertMany() method to bulk-insert an array of model data.
// seed.js:1, 110-117
const db = require("./app/models");
// ...
db.mongoose.connect(db.url)
.then(() => {
const Model = db.models;
Model.insertMany(modelsData)
.then(() => {
console.log("Models seeded!");
process.exit(0);
})
.catch(err => console.log(err));
})
Sources: seed.js:1, seed.js:110-117