---
title: "Write a Node.js script to seed your MongoDB database with sample data."  
description: "Write a Node.js script to seed your MongoDB database with sample data."  
author: "Steilla Mitchel"  
published: 2023-07-26  
updated: 2023-07-27  
canonical: https://www.mindstick.com/forum/159310/write-a-node-js-script-to-seed-your-mongodb-database-with-sample-data  
category: "node.js"  
tags: ["javascript", "node js", "mongodb", "mern"]  
reading_time: 2 minutes  

---

# Write a Node.js script to seed your MongoDB database with sample data.

Write a [Node.js](https://www.mindstick.com/articles/1499/upload-and-download-file-in-node-js) [script](https://www.mindstick.com/interview/477/how-can-i-execute-a-php-script-using-command-line) to [seed](https://yourviews.mindstick.com/story/4868/9-reasons-why-pumpkin-seed-is-a-superfood) your [MongoDB](https://www.mindstick.com/articles/337565/understanding-document-stores-a-look-at-mongodb-vs-couchdb) [database](https://www.mindstick.com/articles/12226/use-of-database-in-sencha-extjs-and-insert-record-from-user-form-using-ajax) with [sample](https://www.mindstick.com/news/2174/mars-mission-by-nasa-prepares-for-tests) data.

## Replies

### Reply by Aryan Kumar

Sure, here is a Node.js script to seed your MongoDB database with sample data:

JavaScript

```plaintext
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/mydb';

const seedData = [
  { name: 'John Doe', age: 30, address: '123 Main Street' },
  { name: 'Jane Doe', age: 25, address: '456 Elm Street' },
  { name: 'Peter Smith', age: 40, address: '789 Oak Street' },
];

async function seedDatabase() {
  const client = await MongoClient.connect(url);
  const db = client.db('mydb');

  const collection = db.collection('people');
  await collection.insertMany(seedData);

  console.log('Database seeded successfully');
}

seedDatabase();
```

This script first imports the `MongoClient` module from the `mongodb` package. It then defines the MongoDB connection URL, which is `mongodb://localhost:27017/mydb`.

Next, the script defines an array of sample data. The sample data consists of three people, with their names, ages, and addresses.

The `seedDatabase()` function then connects to the MongoDB database and gets the `people` collection. The function then inserts the sample data into the collection.

Finally, the `seedDatabase()` function logs a message to the console indicating that the database has been seeded successfully.

To run this script, you can save it as a file called `seed.js` and then run it from the command line:

```plaintext
node seed.js
```

This will seed your MongoDB database with the sample data.


---

Original Source: https://www.mindstick.com/forum/159310/write-a-node-js-script-to-seed-your-mongodb-database-with-sample-data

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
