Backend Server Setup
Relevant source files
The following files were used as context for generating this wiki page:The backend for the LostData project is a Node.js application built using the Express framework. Its primary purpose is to provide a RESTful API for managing a database of "models". The server handles data persistence using MongoDB, manages user sessions for authentication and authorization, and exposes endpoints for CRUD (Create, Read, Update, Delete) operations, as well as data import/export functionalities.
The architecture is centered around a single server.js file which defines the server logic, middleware, and API routes. It connects to a MongoDB database, defines a data schema for models, and serves a static frontend application. The system includes a simple role-based access control mechanism to distinguish between regular users ('chatter') and administrators ('admin'), with certain actions restricted to admins.
Sources: server.js, APP/models/model.model.js
Core Technologies & Dependencies
The backend relies on several key Node.js packages to function. These are defined in package.json and managed by npm.
| Package | Version | Description |
|---|---|---|
express | ^5.1.0 | The core web application framework used to build the server and API. |
mongoose | ^8.19.0 | An Object Data Modeling (ODM) library for MongoDB, used for schema definition and database interaction. |
cors | ^2.8.5 | Middleware to enable Cross-Origin Resource Sharing, allowing requests from any origin (*). |
dotenv | ^17.2.3 | Loads environment variables from a .env file into process.env. |
express-session | ^1.18.2 | Middleware for managing user sessions, used for authentication. |
multer | ^2.0.2 | Middleware for handling multipart/form-data, used for file uploads (CSV import). |
csv-parser | ^3.2.0 | A streaming CSV parser used to process uploaded CSV files for data import. |
json2csv | ^6.0.0-alpha.2 | A converter to parse JSON data into CSV format for data export. |
Sources: package.json:2-10, server.js:2-9
Server Initialization and Middleware
The main server entry point is server.js. It initializes an Express application and configures several middleware components that process incoming requests before they reach the route handlers.
The following diagram illustrates the request flow through the configured middleware.
This diagram shows an incoming request passing through the chain of Express middleware.
Sources: server.js:12-23
Middleware Configuration
cors: Allows requests from any origin, which is useful for development and simple API access.
app.use(cors({ origin: "*" }));express.json&express.urlencoded: Parse incoming request bodies with JSON payloads and URL-encoded payloads, respectively.express-session: Creates a session for each user. The session data is stored on the server and is used to maintain login state.express.static: Serves static files (HTML, CSS, JS) from thepublicdirectory. This is how the frontend application is delivered to the user's browser.- Catch-all Route: A special route
app.get(/^\/(?!api).*/, ...)ensures that any request that does not start with/apiis served the mainindex.htmlfile, which is typical for Single Page Applications (SPAs).
Sources: server.js:12-23, server.js:189-191
Database Configuration and Model
The application uses MongoDB as its database, with Mongoose as the ODM to interact with it.
Database Connection
The connection URI is managed via APP/config/db.config.js, which pulls the URI from the MONGODB_URI environment variable or defaults to a local MongoDB instance. The connection is established in server.js.
// APP/config/db.config.js
module.exports = {
url: process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/model_db"
};
Sources: APP/config/db.config.js:2-4, server.js:25-26
The APP/models/index.js file serves as a central point for aggregating the database configuration and all Mongoose models. It exports a db object containing the Mongoose instance, the connection URL, and the defined models.
Sources: APP/models/index.js:3-11
Model Schema
The data structure for a "model" is defined in APP/models/model.model.js. This schema dictates the fields, types, and constraints for each model document stored in the database.
The diagram below represents the Model schema.
This ER diagram shows the fields and types defined in the Mongoose schema for a Model.
Sources: APP/models/model.model.js:2-15
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 | Pricing information for the model's services. |
dosAndDonts | String | required | A list of allowed and disallowed activities. |
extraTabs | Array | default: [] | An array for additional information tabs. |
history | Array | default: [] | An audit log of changes made to the model document. |
A pre('save') Mongoose hook is defined to automatically update the history array whenever a document is modified, logging the timestamp, action, and modified fields.
Sources: APP/models/model.model.js:2-26
Authentication and Authorization
The server implements a simple session-based authentication system with two user roles: chatter and admin.
Authentication Flow
- A user sends a
POSTrequest to/api/loginwith their email. - The server determines the user's role based on the email address. If it ends with
@admin.com, the role isadmin; otherwise, it ischatter. - A session is created for the user, storing their email and role.
- The role is sent back to the client, which can then adjust the UI accordingly.
- To log out, the client sends a
POSTrequest to/api/logout, which destroys the session.
The following sequence diagram illustrates the login process.
This diagram shows the sequence of events during a user login request.
Sources: server.js:28-32, public/index.html:81-92
Authorization
Authorization is enforced by the isAdmin middleware. This function checks if a user is logged in (req.session.user exists) and if their role is admin. If not, it returns a 403 Forbidden status. This middleware is applied to all routes that perform destructive or sensitive operations, such as creating, updating, deleting, or exporting data.
// server.js:40-43
const isAdmin = (req, res, next) => {
if (req.session.user && req.session.user.role === 'admin') next();
else res.status(403).json({ message: 'Admin required' });
};
Sources: server.js:40-43
API Endpoints
All API routes are defined directly in server.js. They provide the interface for the frontend to interact with the model data.
| Method | Path | Admin Only | Description |
|---|---|---|---|
POST | /api/login | No | Logs a user in and creates a session. |
POST | /api/logout | No | Logs a user out and destroys the session. |
GET | /api/models | No | Retrieves a list of all models, sorted by name. |
GET | /api/models/:id | No | Retrieves a single model by its ID. |
POST | /api/models | Yes | Creates a new model. |
PUT | /api/models/:id | Yes | Updates an existing model by its ID. |
DELETE | /api/models/:id | Yes | Deletes a model by its ID. |
GET | /api/export/json | Yes | Exports all model data in JSON format. |
GET | /api/export/csv | Yes | Exports all model data in CSV format. |
POST | /api/import/csv | Yes | Imports model data from an uploaded CSV file. |
Sources: server.js:28-187
Model Creation Flow (Admin)
The following diagram shows the process of an admin user creating a new model.
This diagram details the steps involved when an admin creates a new model via the API.
Sources: server.js:75-84
Data Seeding and Management
Database Seeding
The seed.js script is a standalone utility for populating the database with initial data. It connects to the MongoDB instance, defines an array of model objects (modelsData), and uses Model.insertMany() to bulk-insert them into the database. This is useful for setting up a development environment or deploying the application for the first time.
Sources: seed.js
Python CLI Tool
The repository also contains model_database.py, a Python script that provides a command-line interface for managing model data in a local models.json file. While it operates independently of the Node.js backend and uses a different data store (JSON file vs. MongoDB), its functionality (add, remove, view, list models) mirrors the core purpose of the main application. It serves as an alternative or supplementary tool for data management.
Sources: model_database.py
Summary
The backend of the LostData project is a well-structured, albeit simple, Node.js/Express server. It effectively uses middleware for handling requests, sessions for authentication, and Mongoose for database interactions. The clear separation of roles and protected endpoints provides a basic but functional security model. The inclusion of data import/export features and a database seeding script makes it a complete system for managing the "Model Database".