DEV Community

FredAbod
FredAbod

Posted on

How To Easily Seed Data Into MongoDB Using Faker

I've Always Always looked for a very Easy and Stress-Free way of seeding data into my database until I found FAKER 🕊🕊

First Of What is FAKER?

Faker is a popular npm package that generates realistic fake data for a variety of data types, including names, addresses, phone numbers, dates, and more. It is often used by developers to quickly generate test data or to populate a database with sample data for testing or demonstration purposes.

Faker is available as an npm package, which means it can be easily installed and used in any Node.js project. To install Faker, simply run the following command in your terminal:



npm i faker


Enter fullscreen mode Exit fullscreen mode

Once installed, you can use Faker in your Node.js project by importing the Faker module and calling its methods to generate fake data.


Faker provides a wide range of methods for generating fake data, including:
*faker.name: generates fake names (first name, last name, full name, etc.)
*faker.address: generates fake addresses (street address, city, state, zip code, etc.)
*faker.phone: generates fake phone numbers
*faker.internet: generates fake email addresses, usernames, and passwords
*faker.date: generates fake dates and times
*faker.lorem: generates fake text (words, sentences, paragraphs, etc.)

In addition to these basic data types, Faker also provides methods for generating fake data for specific industries or use cases, such as finance, healthcare, and ecommerce.

Overall, Faker is a powerful tool for generating realistic fake data quickly and easily in Node.js projects. It can save your time and effort when testing and developing applications that require large amounts of data, and it can help ensure that data is properly formatted and structured.

To get started😉😉 create a Folder and give it any name you want as for me I'll name mine "Easy Seeding😎"
Open your Folder in your IDE(Integrated Development Environment) mine is VScode and open your terminal in there:-):-)
Then

npm init-y

This will create a package.json file for you
Next Up:

touch index.js

This will create a new JavaScript file for you "index.js"
Next Up:

npm i mongoose faker

This would install Mongoose and faker under your dependencies in the package.json folder
Next Up: We'll edit our script file in the package.json folder
From This:



 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },


Enter fullscreen mode Exit fullscreen mode

To This:



"scripts": {
      "test": "node index.js"
    },


Enter fullscreen mode Exit fullscreen mode

Now to the Body of our Code
We'll firstly import Mongoose and connect to our Database



const mongoose = require('mongoose');
const connectDB = async () => {
    try {
      await mongoose.connect("mongodb://localhost:27017/seeding_tutorial");
      console.log("connected to db");
    } catch (error) {
      console.error(error);
    }
  };
connectDB()


Enter fullscreen mode Exit fullscreen mode

This is my database url:

mongodb://localhost:27017/seeding_tutorial
Run the Command

npm test

You Should get the message "connected to db" If you've done everything right😉😉

Next Up:
Lets create our Schema:

touch user.schema.js

Add This Line Of Code In This File



const mongoose = require("mongoose");
mongoose.set("strictQuery", true);

const userSchema = new mongoose.Schema(
  {
    fullName: {
      type: String,
      trim: true,
    },
    reviews: {
      type: String,
    },
    ratings: {
      type: Number,
      enum: [1, 2, 3, 4, 5],
    },
    email: {
      type: String,
      required: [true, "Please enter an email"],
      trim: true,
    },
    password: {
      type: String,
    },

    location: {
      type: String,
    },
    category: {
      type: String,
    },
  },
  {
    timestamps: true,
    versionKey: false,
  }
);

module.exports = mongoose.model("User", userSchema);


Enter fullscreen mode Exit fullscreen mode

Now lets Import Our Schema Into Our Main-entry File which is index.js



const user = require('./user.schema');


Enter fullscreen mode Exit fullscreen mode

Add The line of code above to line2
Next Up;
We'll be importing faker



const faker = require('faker');


Enter fullscreen mode Exit fullscreen mode

Then:




const generateUsers = (num) => {
  const user = [];

  for (let i = 0; i < num; i++) {
    const fullName = faker.name.firstName();
    const ratings = faker.datatype.number({ min: 1, max: 5 });
    const reviews = faker.lorem.sentences(3);
    const location = faker.lorem.sentences(1);
    const password = faker.datatype.number();
    const email = faker.internet.email();
    const category = faker.commerce.department();
    const createdAt = faker.date.past();

    user.push({
      fullName,
      reviews,
      category,
      ratings,
      password,
      category,
      email,
      location,
      createdAt,
    });
  }

  return user;
};


Enter fullscreen mode Exit fullscreen mode

The lets add the number of users we want:



const user = generateUsers(50);


Enter fullscreen mode Exit fullscreen mode

This would generate 50 fake users
Then let faker do its thing



User.insertMany(user)
  .then(docs => console.log(`${docs.length} users have been inserted into the database.`))
  .catch(err => {
    console.error(err);
    console.error(`${err.writeErrors?.length ?? 0} errors occurred during the insertMany operation.`);
  });


Enter fullscreen mode Exit fullscreen mode

And We're done 😉😉😉
RUN

npm test

Now You should see
connected to db
50 users have been inserted into the database.

I Hope You Found This Useful

My DB

Top comments (0)