Install the latest MongoDB Community Server.
Verify you can run mongod
and mongo
from your command prompt or terminal
(If you can't, Google "configure path variable" for your platform. You need to add the mongo\bin directory to your path.)
Decide where you want your data directory to live. Assuming you are on a lab PC, let's say your StarID is ab1234cd so you'd like it to be at C:\Users\ab1234cd\data\db.
You'll need to create that data\db directory.
Start mongod like this
mongod --dbpath C:\users\ab1234cd\data\db
Open another command prompt, and type
mongo
To start the mongo shell. At this point, you can run any commands you like. But so can everyone else, so let's set up authentication. You need
- one user administrator user, who should have a GOOD password, and will create and manage other users
- one other DB user, also with a good password, who will be used to connect on behalf of your web app.
In the mongo shell, type the following, but replace abc123 with a good password, and remember it.
You could use special characters and spaces, but you'll need to escape them to connect, so use a long alphanumeric password with no spaces or characters that are special characters in a URL.
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
And, create a new gardener
user to manage an example database called garden
. Replace the password with something more secure.
use garden
db.createUser(
{
user: "gardener",
pwd: "flower",
roles: [ {role: "readWrite", db: "garden"} ]
}
)
type exit
to quit the shell, and press Ctrl+C to stop mongod.
Now restart mongo, but this time, require authentication,
mongod --auth --dbpath C:\users\ab1234cd\data\db
And restart the shell with mongo
.
Authenticate your gardener
user like so,
db.auth("gardener", "flower")
Now your gardener user can read and write data, e.g.
db.flowers.insertOne({"name":"rose", "color":"pink"})
db.flowers.find()
In Express, you'll connect to your MongoDB with a URL that includes your gardener
user's username and password.
We don't want to put the username and password in code. Instead, we'll configure an environment variable with the URL. You'll also do this on Heroku or wherever your app is deployed.
The URL must be in the format
mongodb://USERNAME:PASSWORD@localhost:27017/DATABASE
- Set an environment variable.
On a PC
set MONGO_URL=mongodb://gardener:flower@localhost:27017/garden
On Mac/Linux
export MONGO_URL=mongodb://gardener:flower@localhost:27017/garden
And then to connect in app.js,
var mongo_url = process.env.MONGO_URL;
MongoClient.connect(mongo_url, function(err, db) {
....
});