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

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay