Make Your Life Easier on MongoDB Atlas
Database seeding made easy while deploying to Heroku.
While building a progressive web application using create react app with the intent to deploy to Heroku, I discovered there wasn’t a whole lot of information regarding the tasks I needed to complete. I want to touch on one specific topic that seemed to only have one solution I kept coming across in my quest to find the best method. Seeding a MongoDB Atlas cluster. For the purposes of this article, I am going to assume you already know how MongoDB works, how to setup the initial cluster, and how to connect it to your application through environment variables.
To start, let’s discuss the only solution I kept coming across while searching for an answer to my dilemma. The solution is a simple one, but requires an unnecessary amount of work. Every resource stated that you need to seed the initial database using .json files. Sure, I could have done a quick copy and paste of my database seeds into .json format and uploaded those to the database. But why? I also could have written a quick function to use the built-in node.js file system to create my .json files for me. But again, why? Every method I kept thinking up inevitably led me to ask myself why I needed to do it that way.
My epiphany came when I started to think about the process for deploying my application to Heroku. During deployment through the command line interface, Heroku runs several scripts from the package.json file. I had a “seed” script in my package.json file in the server directory and a “seed” script in my package.json file in the root directory that called my server directory script. What I noticed during the deployment process was that Heroku was only looking for my “install” script to install the dependencies from my client and server directories and a “heroku-postbuild” script to run my “build” script from the client directory.
Once I broke down the build process, I thought that it might just be possible to hack into it to seed my database. That was when I decided to add my “seed” script to my “heroku-postbuild” script. So starting with a completely empty cluster on MongoDB Atlas, I decided to push my application to Heroku with the now modified “heroku-postbuild” script. After the build process had completed, I checked my MongoDB Atlas cluster and sure enough it was now seeded with my database and associated collections.
I hope this article will help anyone that is looking for an alternative to what seems to be the traditional method for seeding a MongoDB Atlas cluster. Even if you aren’t dealing with the exact same set of circumstances with your application, hopefully this explanation will help you to think of a similar solution that works just as easily.
You can let me know if this helped you by hitting the clap icon or leaving a comment. I would greatly appreciate any feedback and let me know if there are any other issues you would like me to look into for future articles.