Database seeding in Node.js (2024)

Next, we write the Node.js script, which is required to establish a database connection and execute the SQL snippet we just created.

The Node.js script: ./db/index.js

Database seeding in Node.js (1)

What happens here?

  1. Load the environment variables using dotenv
  2. Read the SQL snippet
  3. Connect to the database (MySQL)
  4. Generate a random password (hashed)
  5. Execute the SQL snippet

At the end, the admin password is logged to the console if everything worked fine. Instead of using dotenv you can also use fs.readFileSync to load your database credentials from any other file.

If you’re not using MySQL you simply have to modify the database connection setup. I’m sure there’s an npm package for your database system that can handle this.

Last but not least let’s extend the package.json scripts to simplify the execution of the Node script.

{
"scripts": {
// ...
"seed": "node db/index.js"
// ...
}
}

Now you can run the database seeding with a single command from the terminal: npm run seed. That’s it! Your database is filled with dummy data and you can focus on the important stuff.

There’s also a GitHub repository available including an example application that makes use of database seeding. Have a look.

Database seeding in Node.js (2024)
Top Articles
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated:

Views: 6122

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.