DEV Community 👩‍💻👨‍💻

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

Posted on

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

Top comments (0)

DEV has this feature:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠