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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs