How to use Mongo Seeding CLI with Express and Mongoose

Dalthon Mamani
3 min readMar 31, 2020

--

If you’re using a no-relational database like Mongodb, you should keep in mind that test data is very important because help to us testing data very similar to we will be used in a production enviorement, we dont use a faker because not always they adapt to our purposes, so in this post I wanted to make a small example of importing data using a backend express + mongodb + mongoose and mongo-seeding-cli system.

For this, I separated it into four important points:

1. Have the data odel

To seed your database, using mongo seeding cli, you must have the idea of ​​the datamodel that you require, for example take the case of a restaurant, it contain the following documents in mongodb (tables in a relational database ), users, plates and orders, note that there are a relation between plate and order models.

User.js

Plate.js

Order.js

2. Have the information

We must have the data and it shoud be structured like Paweł says, using the Import data definition guide, in this example we use the following directory structure:

To be more specific with our example, we use this json files:

Users.json

Plates.json

Orders.json

3. Mongo-seeding-cli installation and execution

To use it in more than one project, we install it globally with this command:

$ npm install -g mongo-seeding-cli

After install, we could use the command seed that give us the package, to use the command we must to know the string of conection with the database, so before we must be sure of the route to direct the data folder, in this example we’re in:

$ pwdE:\mongo-seeding\examples\import-data-json\example>

After to be sure the we’re correctly in the route, we use the command:

$ seed -u mongodb://127.0.0.1:27017/restaurant --drop-database ./data

When we execute the command above, it does not give us a message but if you look at your database GUI you will notice that you already have your tables populated with the information that we have placed.

Data in the database after seed it with mongo seeder CLI

4. Fetch data with mongoose populate

As I mentioned that express is used, to bring the defined relation of plates and orders we must use the populate function of mongoose, whose function would be the following:

To test our API, using Postman, this function will return the information to us as follows:

This example you could found in Github to clone it and prove!

I appreciate your attention in this post, I hope to collaborate in future … greetings from ~ Dalthon.

--

--