Thought leadership from the most innovative tech companies, all in one place.

How to Seed MongoDB Database From Node: The Simplest Way

image

Imagine you're building a CRUD app with express and mongoose and you need to test the CRUD functionality you implemented. You need data in your database right. Seeding your MongoDB database can help you to get some data within your Mongo collection and thus will enable you to test out your queries without being restricted. Seeding in its simplest way is more like inserting some dummy data initially into the database so that you can play around with it.

The best practice is to create a separate, independent file away from your other app-related files just for this purpose. You can then run the seeding file anytime you want to inject some data into your database.

Mongoose is basically the communicator between Node js and Mongo DB. Mongoose can help you create a connection to your Database through Node. Once you create your Model, defining how you want your Mongo collection should be, then you should be seeding the collection but from a separate file. You can do this from the Model itself but like I mentioned, it would be a good gesture to place that code inside a separate file.

This is my simple model for 'Product' (product.js). Connection with MongoDB is established in 'app.js' file so that I don't have to repeat the connection code in every model file.

models/product.js

models/product.js

Here's the part from my 'app.js' file which establishes the connection.

app.js

app.js

Now, it's time to create the 'seeds.js' file. You can type in data if you want or you can use faker.js to generate some fake data conveniently. Create 'seeds.js' file and start by requiring mongoose. In the model that we created, we didn't establish the DB connection. But in our 'seeds.js' file, we should go ahead and create the connection because that file is supposed to stand by its own feet without depending on any other file, so that it can be used independently to seed the database.

seeds.js

seeds.js

Now you can run 'node seeds.js' command from your terminal to run the file and it will delete all the existing records in DB, if any, and will replace them with the ones you provided. If you don't want to delete existing records, you can simply get rid of Product.deteleMany({}).

Well, that's a short demo on how you can seed MongoDB. Hope you liked it. See you next time!




Continue Learning