Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
bcryptjs is not working inside a mongoose schema method

bcryptjs version: "bcryptjs": "^2.4.3"

mongoose version: "mongoose": "^6.0.12"

I am trying to encrypt user password on user creation or password update. Data is inserted successfully but the password is not encrypted. This is my schema (I copied it from my previous project which was working correctly):

import mongoose from 'mongoose'
import bcrypt from 'bcryptjs'

const userSchema = mongoose.Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true
    },
    password: {
      type: String,
      required: true,
      unique: true,
    },
    votedFor: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Election'
      }
    ],
    finishedVoting: {
      type: Boolean,
      required: true,
      default: false
    },
    isAdmin: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  {
    timestamps: true,
  }
)

userSchema.pre('save', async function(next) {
  // Only run this function if password was actually modified
  if (!this.isModified('password')) return next();

  // Hash the password with salt 10
  this.password = await bcrypt.hash(this.password, 10);

  next();
});

In the database, I see the password as a plain text(unencrypted). So I tried using callback function instead of async/await as suggested in other answers:

userSchema.pre('save', function(next) {
    var user = this;
    console.log("encryption")

    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password')) return next();

    console.log("started encrypting")

    // generate a salt
    bcrypt.genSalt(10, function(err, salt) {
        if (err) return next(err);

        // hash the password using our new salt
        bcrypt.hash(user.password, salt, function(err, hash) {
            if (err) return next(err);
            // override the cleartext password with the hashed one
            user.password = hash;
            next();
        });
    });
});

Did not help. I deleted the collection and re-inserted the data. Again the password remains unenrypted. I did not see console.log("encryption") nor console.log("started encrypting") while inserting. This is some users data that I am inserting:

const voters = [
  {
    username: "194199",
    password: "FA654644", //will be encrypted
    isAdmin: false,
    finishedVoting: false
    // votedFor: [Object], //
  },
  {
    username: "184183",
    password: "MB454644", //will be encrypted
    isAdmin: false,
    finishedVoting: false
    // votedFor: [Object], //
  },
  {
    username: "194324",
    password: "FA651684", //will be encrypted
    isAdmin: false,
    finishedVoting: false
    // votedFor: [Object], //
  }
]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

i have the same problem but with bcrypt-nodejs.

😐

about 4 years ago · Kikiriya Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda