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

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay