How I used MongoDB, ExpressJS, VueJS and NodeJS — and my favorite Blue Apron recipes — to make meal prep easier for my wife and I.
I subscribe to Blue Apron, one of several fresh meal delivery services.
Each week, I receive a box containing the ingredients and three sheets of paper, one for each meal. The sheet has all the information necessary to prepare the meal.
Over time, I have accumulated hundreds of these sheets, many for meals that my wife and I didn’t particularly enjoy. But several were delicious, and we may want to buy our own ingredients to make them again.
Blue Apron has a fantastically well-designed and useful mobile app. It makes meal-planning, delivery scheduling, and order issue reporting as easy as I could hope.
But the app does not feature the same cookbook as is found on their website, at blueapron.com/cookbook.
Nor does the app allow me to create my own weekly meal plans using recipes from its rich and expansive cookbook.
Lastly, Blue Apron uses a Google Firestore database to store each of the recipes found in its cookbook. Yet, sadly, it does not make a public API available such that I could request a full list of recipes.
Each box of ingredients comes with a one-pager.
Between the front and back sides, the following information can be found:
I will later codify this information as the schema for one of the collections in my database.
This project was an excuse to familiarize myself better with the popular NoSQL database, MongoDB.
Lucky for me, enacting each of the steps necessary to create a database and collection, connect to it, and manually insert the first document…is all made easier thanks to MongoDB’s well-written and straightforward documentation.
Let’s see a few key steps:
Visit https://cloud.mongodb.com/user#/atlas/register/accountProfile to create an account
Or visit https://cloud.mongodb.com/user?nds=true#/atlas/login if you have one already
When creating a new project, you have to give it a name and a member.
Once you have a project, you can build a cluster.
You are allowed one M0 cluster per project. M0 offers 512MB and shared RAM and vCPU…and is free!
M0 Sandbox cluster tier is ‘Free forever’. You can have one per project.
I created a new free cluster and called it BlueApron
With my cluster created, I need to connect to it…somehow.
This button shows three options for connecting to a cluster
MongoDB created a GUI to manage clusters. It’s called Compass.
Download and install Compass. Open it. Then click ‘Copy’.
Compass will auto-populate all required fields except your password.
Don’t forget to click ‘Create Favorite’ so you can connect with 1-click next time.
Once connected, you need to create a database and a collection.
To create a database, you must also create a collection
I created a database named ‘meals’ and my first collection is ‘recipes’.
MongoDB stores BSON documents. They look near-identical to JSON. As a JavaScript developer, this makes working with them feel very intuitive.
Earlier I mentioned the five important pieces of information found on each recipe card.
Let’s convert that information into a BSON document schema:
{
"name": string,
"sides": string,
"photo": string,
"main_ingredient": string,
"time": [
"min": integer,
"max": integer
],
"servings": integer,
"ingredients": [
{
"name": string,
"quantity": string
},
...
],
"instructions": [
{
"heading": string,
"steps": string
},
...
]
}
MongoDB will add an _id
key and value to this document when it is inserted into the collection, thankfully.
mongo
shell and inserting a documentIf you don’t have it installed, there are instructions to do so using the service, brew
.
Once installed properly, the guide offers a copy-able string that you must enter in your command line, like this:
mongo "mongodb+srv://cluster-name.mongodb.net/test" --username yourusername
Running this command will prompt you for your password, then hopefully establish a connection
There are many handy guides offered by MongoDB. The one below shows how to insert one document into a collection.
How to insert a single document into a collection
Here I verified I’m using the correct database and collection. Then I simulate an ‘insertOne’ call
If successful, then back in Compass, you should refresh and see your first document.
Our first document added to the first collection in our first MongoDB cluster
My wife and I collected all of the recipe cards from the cupboard and made two piles:
I recycled the first group, and placed the second group in my desk cubby to insert manually later.
Blue Apron has a place on their website called Cookbook where anyone can browse their entire…cookbook.
Blue Apron’s official cookbook
Clicking a thumbnail leads to the full recipe page
Right-clicking the image lets me ‘Copy image address’ and use it in my document
https://media.blueapron.com/recipes/22413/square_newsletter_images/1566315246-34-0087-2844/0923_W5_Tuscan-Pork_6138_SQ_Web_hi_res.jpg
All links point to media.blueapron.com
so I’m confident they won’t break anytime soon.
Sadly, I can’t expect my wife to download MongoDB Compass on her iPad, iPhone or work computer in order to browse recipes, set weekly meal plans, or add recipes.
To be fair, I wouldn’t want to do that, either.
No, what we both need is an intuitive interface where we can browse by looking at pictures of the food, press buttons to see ingredients or steps, and have handy links to view this week’s menu and the larger cookbook.
Suffice it to say…I need to build a bridge from the database to our phones such that when interacting with elements on a web page, the browser sends requests to a server which performs specific database queries and returns the expected results back to the browser, updating the page in real-time.
That means I need:
Each of those bullets comprises one layer in what is commonly referred to as a ‘stack’.
For the JavaScript community, this stack has a handy acronym:
That spells ‘ME*N”. What’s the *? It depends on which of the three currently popular JavaScript frameworks you decide to use
I used a stack whose acronym feels the oddest to say, but in my opinion is the most accessible to JavaScript newcomers: MEVN.
To properly develop and test this app on your computer, you need Node and its cousin, npm
.
There are many ways to install Node and npm
.
You could download and install it directly from nodejs.org.
Or you could use a package manager like Homebrew, if you’re using MacOS.
Sadly, in order to proceed, I must assume you have both Node and npm
installed, and that you’re using MacOS.
$ cd ~/Downloads/
$ mkdir meal-prep-app
$ cd meal-prep-app
$ npm init
We create a new directory in the Downloads folder, called meal-prep-app
, and use npm init
to create the common, necessary node-related files.
$ npm install express
With express
package installed, we can begin crafting the program that will serve our application files and soon respond to requests.
$ touch server.js
File: server.js
const express = require('express');
const PORT = process.env.PORT || 5000
const app = express();
app.listen(PORT, () => console.log(`Example app listening on port ${PORT}!`));
In four lines, we created an express app and told it to listen on port 5000.
Entering either command below in your terminal should display that last line of text. Congrats! (hopefully?)
$ node server.js
or
$ npm start
...
Example app listening on port 5000
We created an express app and told it to listen for requests.
Next, let’s setup some empty ‘routes’ that our app will eventually respond to with data from our MongoDB cluster…when a user visits a specific URL endpoint by using the app.
Still in server.js
:
...previous lines
app.get('/api/meals', (req, res) => {
// TODO: query database for all documents in 'recipes' collection
}
app.get('/api/menu/', (req, res) => {
// TODO: query database twice
// Once for the most recent document added to a collection
// that stores weekly menus
// Then again for all documents in 'recipes' collection
// that intersect with IDs in the document returned earlier
}
app.get('/api/steps/:id', (req, res) => {
// TODO: query database for 'steps' array
// of document in 'recipes' collection that matches an ID
}
app.get('/api/instructions/:id', (req, res) => {
// TODO: query database for 'instructions' array
// of document in 'recipes' collection that matches an ID
}
app.post('/api/menu', (req, res) => {
// TODO: insert document in 'menus' collection
// that will include an array of recipe document IDs
}
Five endpoints. Four of type GET
. One of type POST
.
We will expand on each one in the next section.
Within the body of each endpoint shown above, we need to establish a connection to our MongoDB database and respective collection, then perform a query to either find or create one or more documents.
Much like earlier with express, we must install a package, import it into our program, and initialize a few settings:
$ npm install mongodb
Back in server.js
:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster.mongodb.net/database-name?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
First, we import (via require()
) our mongodb
package, and immediately return the object stored in MongoClient
.
Then we store a reference to the connection string that MongoDB Atlas provided to us.
Lastly, we create a new instance of the MongoClient
, passing the connection string and a few important configuration options bundled into a single object.
Now we are ready to connect, query, and return data from our database inside the first endpoint:
app.get('/api/meals', (req, res) => {
client.connect(err => {
if (err) console.log(err);
const collection = client.db("meals").collection("recipes");
collection.find({}).toArray((err, docs) => res.jsonp(docs));
client.close();
});
}
This first endpoint should return all of the documents in the recipes
collection in the meals
database.
Using our client
object, we call connect
, passing it an anonymous function that may take a single parameter, err
.
Inside this anonymous function, we immediately log an error if one is thrown.
We use client
’s db
method to connect to the meals
database, then the collection
method of that object to get a reference to the recipes
collection. All of this is saved in the constant, collection
.
Now, in a single line, we query the database using the find
method, passing an empty object as a way to query the entire collection. What’s returned is a Promise
that hopefully resolves to a cursor
that we immediately end as an array. Assuming there are no errors, we finally return the contents of that array — stored within the confines of this last anonymous function as docs
— as parsed JSON.
Lastly, we close the connection to the database.
If you want to learn more about MongoDB through first-party online training, visit MongoDB University.
Now that we have an API endpoint, let’s make sure it works as expected.
First, start your local server in your terminal:
$ npm start
or
$ node server.js
We’ll use Postman, a free app that lets us perform test API requests.
Download, install and open it.
Close the pop-up.
Where you see the word ‘GET’ in a dropdown menu, enter:
localhost:5000/api/meals
Assuming you see something that looks like what’s in the screenshot above, congratulations! You used Postman to send a GET
request to an API
that you built using Node, Express and MongoDB!
In efforts to keep things a bit more familiar to me, I opted not to make this app a single-page application, or SPA.
Instead, I point Express at a single folder. Inside that folder are a few HTML pages with their respective JavaScript files and a shared CSS file.
This is not the most intuitive approach.
However, this approach doesn’t require additional packages or build tools.
Here’s my directory structure:
meal-prep-app/
--server.js
--public/
----index.html
----cookbook.html
----steps.html
----ingredients.html
----styles.css
----meals.js
----steps.js
----ingredients.js
----menu.js
In essence, it looks like a typical website file structure with multiple HTML files and a shared CSS file. The difference is each of the JS files, which I’m using as hybrid components: each JS file corresponds to an HTML file.
Given the length of this tutorial thus far, I’ll constrain this section to the most intriguing view, cookbook.html
and meals.js
.
The noteworthy portion of cookbook.html
is:
<div id="app" class="section">
<div class="container block">
<h2 class="title is-3">Cookbook</h2>
<div class="buttons">
<meal-filter
@change-selected-ingredient="changeSelectedIngredient"
v-for="ingredient in mainIngredients"
:ingredient="ingredient"
:key="ingredient"
:class="{ 'is-active': ingredient === selectedIngredient, 'is-primary': ingredient === selectedIngredient }"
class="button" />
</div>
<div v-if="meals" class="container">
<meal-item
v-for="meal in filteredMeals"
:meal="meal"
:key="meal._id"
@add-to-menu="addToMenu" />
</div>
</div>
</div>
This code snippet contains a mix of native HTML elements, custom VueJS components and VueJS directives.
The <meal-filter>
and <meal-item>
tags are custom VueJS components. Each of their attributes — or at least what look like attributes — are VueJS directives that enable reactive data bindings, event handlers/emitters, and conditional styling.
Here’s how <meal-filter>
works:
Vue.component('meal-filter', {
props: ['ingredient'],
template: `
<button
@click="$emit('change-selected-ingredient', ingredient)">
{{ ingredient }}
</button>
`,
})
In cookbook.js
I add a globally available custom component called meal-filter
. It expects one property to be passed to it, called ingredient
. Anywhere in my HTML that <meal-filter>
appears, I expect the page to render a <button>
whose text is the name of the ingredient. When a user clicks on this button, I expect the component to emit a custom event which I called change-selected-ingredient
. The event will contain a value that can be referenced via the label, ingredient
. The parent component will then respond to this event:
<div class="buttons">
<meal-filter
@change-selected-ingredient="changeSelectedIngredient" />
</div>
So <meal-filter>
emits the event. The parent component listens for it. When emitted, the parent component will execute a function I wrote, called changeSelectedIngredient
:
new Vue({
el: "#app",
data: {
selectedIngredient: null,
},
methods: {
changeSelectedIngredient(ingredient) {
this.selectedIngredient = ingredient;
this.filterByMainIngredient()
},
filterByMainIngredient() {
this.filteredMeals = this.meals.filter(meal => meal.main_ingredient === this.selectedIngredient)
}
}
})
This code snippet above shows relevant portions of the parent, root Vue component. In the methods
object is the function that gets called with the important ingredient
value. It updates one property in the data
object, then calls another method, filterByMainIngredient
which makes use of the newly updated selectedIngredient
value.
Here’s another small example of how Vue calls our custom API endpoint:
new Vue({
el: "#app",
data: {
meals: null,
filteredMeals: null,
},
mounted() {
this.fetchMeals()
},
methods: {
fetchMeals() {
fetch('/api/meals')
.then(response => response.json())
.then(meals => {
vm.meals = meals;
vm.filteredMeals = meals;
})
}
})
This code snippet shows how, when this same parent Vue component is mounted to the DOM, it calls the custom method, fetchMeals
. In the body of that function, I use the Fetch API
to send a GET
request to my custom endpoint, /api/meals
. When the request resolves, hopefully with no errors, I convert the response to JSON and store it in two of my Vue properties: meals
and filteredMeals
.
The rest of my HTML and JS repeats these patterns for form a working, multi-page, reactive JavaScript application.
If you want to learn more about VueJS by building Google’s Dictionary widget, check out my other tutorial below.
Since the goal of this exercise is to build an app more than it is to specifically improve my CSS-writing abilities…I use a framework called Bulma CSS.
Why choose Bulma?
In order to easily deploy my app using Heroku (in the next step), I need to create and push an initial commit
to a git repository.
Luckily, doing so is quite easy, as long as you already have a git account setup.
After entering all the pertinent information, be sure to add a .gitignore file for Node apps
Once created, you can clone your repo to your computer using the web URL provided
$ git clone <copied url>
Heroku, much like MongoDB, makes deploying web applications feel easier than it should, in my opinion.
Here’s how I setup and deployed this app:
I assume you have a heroku account and downloaded the heroku command line interface, or CLI.
From your dashboard, select New > Create new app
Choose a unique name and click ‘Create app’
Refer to the instructions on Heroku’s ‘Deploy’ tab
$ heroku login
...follow prompts
...assuming you're still in meal-prep-app directory...
$ git add .
$ git commit -m "Publishing so wife can test"
$ git push
$ git push heroku master
Or go a step further and connect heroku directly to your git repo, and turn on automatic deploys:
Choose deployment method 2: GitHub, and connect your repo to enable automatic deploys
My wife and I have used the app for two weeks.
She already has a few change requests.
#nodejs #javascript #express #mongodb