backend/models/ directory. Before the server can handle any requests, a valid MONGODB_URI must be present in backend/.env and the database must be reachable. If the connection fails on startup, the process exits immediately to prevent the app from running in a broken state.
How the Connection Works
Database initialisation lives in a single file,backend/config/db.js. The connectDB function is called once in server.js before any routes are registered:
backend/config/db.js
process.env.MONGODB_URI, which is populated by dotenv when the server starts. There is no explicit database name in the mongoose.connect() call — the database name is embedded in the URI itself (e.g. /food-delivery at the end of the Atlas connection string).
Setting Up Your Database
- Local MongoDB
- MongoDB Atlas
Use a local MongoDB Community Server instance during development when you do not need cloud access.1. Install MongoDB Community ServerDownload and install MongoDB Community Edition for your operating system from the MongoDB download page.2. Start the mongod daemonOn macOS with Homebrew you can instead run:3. Set your connection stringAdd the following to MongoDB will automatically create the
backend/.env:backend/.env
food-delivery database the first time a document is inserted — no manual database creation is required.Data Models
The app defines three Mongoose collections. All models use the patternmongoose.models.<name> || mongoose.model(...) to avoid re-registering a model if the module is imported multiple times.
food Collection
Stores the menu items displayed in the storefront and managed through the admin dashboard.
user Collection
Stores registered customer accounts and their active shopping cart state.
The user schema sets
{ minimize: false } as a schema option. By default, Mongoose removes empty objects from documents before saving them to MongoDB. Setting minimize: false disables this behaviour, ensuring that an empty cartData object ({}) is preserved in the database rather than being stripped out. This is important because the frontend reads cartData on login to restore the user’s cart state.