02 Build MVP fast

Setup MongoDB on local

My source template uses Mongoose to work with MongoDB, with the database hosted on MongoDB Atlas (a cloud-based database service).

We use Mongoose because it provides a simple, schema-based solution to model your application data in MongoDB, making it easier to manage and validate. MongoDB Atlas is chosen for its reliability, scalability, and ease of setup in the cloud—allowing your app to connect securely from anywhere without hosting your own database server.

We will use Docker Compose to run MongoDB. If you do not install Docker Desktop and Docker Compose please to back to this step.


1. Run Docker

To start docker on your system (Window or MAC) please open Docker Desktop:

docker desktop

2. Run MongoDB image on Docker Compose

On our Next.js template, you can see the file docker-compose.yml on the root of folder:

docker compose mongodb
json
version: "3.8" services: mongodb: image: mongo:7.0 container_name: mongodb restart: always ports: - "27017:27017" # Localhost port : Container port environment: MONGO_INITDB_ROOT_USERNAME: admin MONGO_INITDB_ROOT_PASSWORD: password volumes: - mongo-data:/data/db volumes: mongo-data:

On this file, we define the version of mongoDB, user name is admin, password is password. You can change the username and password as you like.

Now open the terminal in your source code then run this command to run docker compose:

bash
docker-compose up -d

Wait for Docker down load the MongoDB image then run it on.

Go back to Docker Desktop, then you can see:

docker compose mongodb run

3. Connect Next.js app to MongoDB

In your source code, in the file .env.local, add this line to connect Next.js app to MongoDB in Docker:

json
MONGO_DB_URI="mongodb://admin:password@localhost:27017/<your_name_DB>?authSource=admin"

You can change <your_name_DB> value base you like.

Now your Next.js app can connect to MongoDB (in the Docker).

4. View database via VS Code

On the local, to easy and fast we can install the MongoDB for VS Code extension on the VS Code to connect and view the MongoDB:

mongodb for VS Code

After install, click on the Add MongoDB Connection -> Click Connect button:

connect mongodb on VS Code

Then paste the MongoDB URI that you save on the MONGO_DB_URI on .env.local file.

After connection, you can see the new connection and view documents:

connected mongodb on VS Code

You have successfully completed the setup 🎉.