This guide will walk you through setting up the project, configuring MongoDB locally, and testing the connection.
- Windows: Download and install MongoDB Community Edition from MongoDB Download Center. (I have not used windows since 2017 so this part could use some expansion if there is more to it than this.)
- Mac (Homebrew):
brew tap mongodb/brew brew install mongodb-community
- Linux (Ubuntu/Debian):
sudo apt update sudo apt install -y mongodb
- Linux (Arch):
yay -S mongodb-bin
MongoDB stores its data in /data/db
by default. Create the directory if it does not exist:
sudo mkdir -p /data/db
To run MongoDB locally:
mongod --dbpath /data/db --auth
If MongoDB is running correctly, you should see a message saying Waiting for connections
or it will just output log information to stdout
.
mongosh
(If mongosh
does not work, try mongo
instead.)
use admin
db.createUser({
user: "adminUser",
pwd: "adminPassword",
roles: [{ role: "root", db: "admin" }]
})
Replace adminPassword
with a strong password.
If MongoDB was running, stop it (Ctrl+C
) and restart it:
mongod --auth --dbpath /data/db
mongosh -u "adminUser" -p "adminPassword" --authenticationDatabase "admin"
use toDo
db.createUser({
user: "yourName",
pwd: "yourSecurePassword",
roles: [{ role: "readWrite", db: "toDo" }]
})
Replace'yourName'
and yourSecurePassword
with your name and a strong password.
mongodb://yourName:yourSecurePassword@localhost:27017/ToDo?authSource=ToDo
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
Create a .env
file inside the server/
directory and add the above like so:
MONGO_URI=mongodb://yourName:yourSecurePassword@localhost:27017/ToDo?authSource=ToDo
JWT_SECRET=a7c99f0c9e6d46f9e0f2b4f5b5e21f98de4e69c7d0b6a3ef40b109c6a6de6a8e
PORT=5000
Ensure that your .env file is in your .gitignore
.env
To verify that MongoDB is running and accessible:
mongosh -u "yourName" -p "yourSecurePassword" --authenticationDatabase "toDo"
If it connects successfully, run:
db.stats()
If it fails to connect, ensure you are using 'yourName' and 'yourSecurePassword'
instead of 'adminUser' and 'adminPassword'
Run the backend:
cd server
node server.js
Then, open a browser and go to:
http://localhost:5000/
Expected output:
API is running...
node server/database/seed.js
cd server
node server.js
cd client
npm install
npm run dev
You have successfully:
- set up MongoDB.
- Created an admin user.
- Configured environment variables.
- Tested connecting to the db.