DEV Community

Aryse Gabrielle Pagano
Aryse Gabrielle Pagano

Posted on

Mongoose DB Seed (node/express)

How do you handle seeding DB during development? When working with mock data during development you constantly find yourself resetting the DB, clearing or manually adding entries to it only to eventually have to clear it again, etc...
If that sounds like you, Here's a mini application that will help you.

Suppose you have an array of objects (your mock data) stored in a file somewhere server-side.

const mockUsers = [
  {
    username: "fakemedic",
    email: "med@med.com",
    password: "$2b$10$h036pK1tWvpYRB3Evbq9j.nk57Zh.OwWtzHXTQhgBbaRhS4LIitsC",
    avatar:
      "https://images.unsplash.com/photo-1463453091185-61582044d556?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cmFuZG9tJTIwcGVyc29ufGVufDB8fDB8fA%3D%3D&w=1000&q=80",
  },
  {
    username: "freesoul",
    email: "free@free.com",
    password: "$2b$10$h036pK1tWvpYRB3Evbq9j.nk57Zh.OwWtzHXTQhgBbaRhS4LIitsC",
    avatar:
      "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cGVyc29ufGVufDB8fDB8fA%3D%3D&w=1000&q=80",
  },
  {
    username: "DaBom",
    password: "$2b$10$h036pK1tWvpYRB3Evbq9j.nk57Zh.OwWtzHXTQhgBbaRhS4LIitsC",
    email: "dabom@dabom.com",
    avatar:
      "https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MzR8fHBlcnNvbnxlbnwwfHwwfHw%3D&w=1000&q=80",
  },
  {
    username: "lastcaique",
    email: "lastcaique@lastcaique.com",
    password: "$2b$10$h036pK1tWvpYRB3Evbq9j.nk57Zh.OwWtzHXTQhgBbaRhS4LIitsC",
    avatar:
      "https://st2.depositphotos.com/3143277/8644/i/600/depositphotos_86446164-stock-photo-business-man-in-office.jpg",
  },
];
Enter fullscreen mode Exit fullscreen mode

In order to make the magic happen we will use process.argv

I personally name the file for my seeder/clearer seed.js.

Let's now get to work:

  1. We require the mock data we will use, along with mongoose, dotenv, and the Models.
const { mockUsers } = require("../db/mock_data");
const mongoose = require("mongoose");
require("dotenv").config();
const { User, Post } = require("../models/models");
Enter fullscreen mode Exit fullscreen mode

2- Store a connection:

const connection = async () => {
  mongoose.set("strictQuery", false);
  await mongoose
    .connect(process.env.DB_URI, { useNewUrlParser: true })
    .then(() => console.log("DB READY TO SEED"))
    .catch((err) => console.log(err));
};
Enter fullscreen mode Exit fullscreen mode

3- Now we create our first function, in my case is to seed. We call the connection function, and simply CREATE, exiting the process when done:

const seedDB = async () => {
  await connection();
  await User.create(mockUsers)
    .then(() => console.log("Users seeded"))
    .catch((err) => console.log(err));

  process.exit();
};

Enter fullscreen mode Exit fullscreen mode

4- Nothing new (hopefully) up to this point... so let's create another function that will clear the DB:

const clearDB = async () => {
  await connection();
  await User.deleteMany()
    .then(() => console.log("Users deleted"))
    .catch((err) => console.log(err));

  process.exit();
};
Enter fullscreen mode Exit fullscreen mode

5- Finally, argv will handle calling those functions, feel free to console.log it at this point, and run the file: node seed.js
You will get an array with paths for index 0 and 1. BUT, if you add a 'flag', it will be the index 2:

node seed.js --my_flag

This log will have the flag as process.argv[2], allowing us to write scripts on package.json to seed and clear:

PACKAGE.JSON:

  "scripts": {
    "start": "NODE_ENV=production node server/index.js",
    "dev": "nodemon server/index.js",
    "seedDB": "node server/db/seed.js --seedDB",
    "clearDB": "node server/db/seed.js --clearDB"
  },
Enter fullscreen mode Exit fullscreen mode

Finally: based on the flag we will call the functions we created:

if (process.argv[2] === "--seedDB") {
  seedDB();
} else if (process.argv[2] === "--clearDB") {
  clearDB();
}

Enter fullscreen mode Exit fullscreen mode

And DONE! Use the scripts to seed and clear anytime you need =)

Top comments (0)