Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
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 Respostas
Responde à pergunta

0

i have the same problem but with bcrypt-nodejs.

😐

about 4 years ago · Kikiriya Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda