Storing Colors in MongoDB

Photo by Magda Ehlers from Pexels

I wanted to practice my database skills with this project, so I decided to incorporate a feature that logged each random color generated by a user request to a Mongo database. I chose MongoDB because my experience with relational databases is fairly limited, and I didn’t want to introduce too much complexity all at once. I knew I’d be comfortable (or at least something adjacent to comfortable) with Mongo’s documents.

This commit has the code I’ll be talking about in this post.

First, I had to install the correct driver from npm. I chose the official driver because it seemed like the obvious option for someone who’s never done this before. Next, I had to establish a connection between my app and Mongo. This part of the docs was very helpful to me. I instantiated a new MongoClient object as they instructed and then called client.connect():

client.connect(function(err, database) {
	assert.equal(null, err);
	console.log("Connected successfully to database server");

	app.listen(PORT, () => {
		console.log(`server running on port ${PORT}`);

Initially, I hard-coded my PORT value, but eventually I wised up and installed dotenv.

I need to test and see if app.listen() needs to be inside the client.connect() callback. I put it there because I didn’t want my app to start until after the connection to the database had been made, but maybe that doesn’t matter. I’ll come back to that another day.

I was expecting to have to create a database and a collection in the shell before I could start coding, but it turns out you can run an insert command on a nonexistent collection in a nonexistent database and both the database and the collection will be created as soon as you insert the data. That’s handy.

My app has two get() handlers, one of which is for the endpoint that generates the random color. In addition to calling my generateColor() function, it takes the returned object and inserts it into the colors collection. Here’s what that get() looks like:

app.get("/api/v1/color", function handleRequest(req, res) {
	console.log("getting a request");
	var color = generateColor();
	db = client.db(dbName);
	var collection = db.collection("colors");
		success: "true",
		message: "color retrieved successfully",

Looking at the code now, I’m wishing that I used the return value of collection.insertOne() to inform what kind of response I sent to the user. According to the docs, the method returns a boolean value indicating the write concern, which indicates whether the insert command was successful. If I had continued with MongoDB, I’d go and change that now, but because I decided to switch to MySQL, it’ll have to wait.

Next up: retrieving the stored colors and serving them up to the user.

Leave a Reply

Your email address will not be published. Required fields are marked *