DEV Community

Cover image for SEED AND HASH PASSWORD IN MONGODB BASED APPLICATION
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

6 1

SEED AND HASH PASSWORD IN MONGODB BASED APPLICATION

_Seeding is the process of providing an initial set of data to a database.

It is useful when we want to insert data into a database that we intend to develop in the future._

However, when seeding our password, we want it to be secure and not in plain text. Here is how to properly seed a database.

Stack: NodeJS, MongoDB, and Express

// =====================SEED AND HASH PASSWORD========================================
const User = require('./models/models.user');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URL);
    console.log('Connected to mongodb');
  } catch (error) {
    console.log(error);
  }
};

connectDB();

(async () => {
  let data = {
    name: 'Abraham Jujin',
    email: 'abe@gmail.com',
    password: 'abe1234',
    phoneNumber: '08168623107',
    role: 'admin',
  };
  let saltRounds = 10;
  let hashedPassword = await bcrypt.hash(data.password, saltRounds);

  data.password = hashedPassword;
  console.log(data.password);

  const seedDatabase = async () => {
    try {
      await User.deleteMany({});
      await User.insertMany(data);
      console.log('Seeding successful');
    } catch (error) {
      console.log(error);
    }
  };

  seedDatabase().then(() => {
    mongoose.connection.close();
  });
})();

Enter fullscreen mode Exit fullscreen mode

Thanks for reading

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay