The Simplest (I Genuinely Promise) Way To Seed/Populate Fake Data In MongoDB Using Node
Tags: mongodb, node
Published: 2021-10-28 22:32:34

Only this short and concise explanation is mine, but credits to [Maximilian Schwarzmüller](https://www.youtube.com/watch?v=V30Rpqi6kYE&t=1s&ab_channel=Academind) from Academind for teaching me this trick.

Hey guys, have you ever wondered how to seed some mock data to your MongoDB database, whether for development/demo purposes or in actual production app? In this article, I will show you the easiest way to populate MongoDB database with very little code, and no, you wouldn't use fancy methods like the following ones.
![Mohmed Ishak](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/435rhitb1qc9pjmzjfdn.PNG)

###Step 1: Make Sure Your Backend Is Up and Running
```javascript
// a bunch of codes go here...
import connectDb from "./utils/connectDb.js";

// MongoDB database connection
connectDb();

// To recognize incoming request as JSON object
app.use(express.json());
// a bunch of codes go here...
```
I bet a portion of your `index.js` or `server.js` file looks like this. The above is just a sample code snippet to make sure we're on the same page. Basically, if your backend which uses MongoDB is up and running, you're all set to seed the data. If not, you can Google how to set up a Node.js and Express.js server and it's easy as there are tons of tutorials teaching you how to do so.

###Step 2: Create Seed Script
Create a file called `seedScript.js` or whatever you want to call it. Before you populate your data, you must have a model/schema, and I'm sure you know that. In this file, all you need to do are 3 things:
* Import relevant model
* Create an array of fake data which will satisfy that model
* Make a simple function to loop through that array and save each documents

Here's a sample. You can copy and paste my code, but change whatever necessary. As for the variable called `done` and function `seedData`, just copy them blindly (if you're rushing) from the following code snippet.
```javascript
import Driver from "../models/driverModel.js";
import mongoose from "mongoose";

const drivers = [
  new Driver({
    name: "Tony Stark",
    location: {
      x: 2,
      y: 4,
    },
  }),
  new Driver({
    name: "Amelia",
    location: {
      x: 6,
      y: 19,
    },
  }),
];

// You can blindly copy the code snippet from the next line onwards
let done = 0;

export const seedData = async () => {
  try {
    await Driver.deleteMany({});

    for (let i = 0; i < drivers.length; i++) {
      drivers[i].save(function (err, result) {
        done++;
      });
    }
  } catch (err) {
    console.error(err);
  }

  console.log("Mock data is seeded from seed script.");
};
```

Here's the explanation. First, all you're doing is creating an array of objects where each object will be saved as document in MongoDB. Then, if you take a look at the `seedData` function, what's happening is that we're deleting previous data (in case you have populated them before) and freshly populating them for every new connection.

###Step 3: Don't Forget to Call That Function
In your `index.js` or `server.js`, or whatever entry point file of yours, just call that function. In this case, I'm calling that function after connecting to database and after using express.json() middleware. It works for me, and I haven't really tried other arrangements.

```javascript
// A bunch of codes go here...

// MongoDB database connection
connectDb();

// To recognize incoming request as JSON object
app.use(express.json());

// Mock data seeding
seedData();

// A bunch of codes go here...
```

That's it. Thank you for reading.