bcryptjs function can perform create operation properly but encounters issues with insertMany operation

bcryptjs package version:

"bcryptjs": "^2.4.3"

Mongoose library version:

"mongoose": "^6.0.12"

Currently, I am working on encrypting user passwords during user creation or password updates. Everything works smoothly when creating a single user using User.create() method as the password gets encrypted successfully. However, when I try to use User.insertMany() to insert multiple users at once, the data is inserted but the passwords are not encrypted. Here is the schema I am using:

const userSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true
    },
    surname: {
      type: String,
      required: true
    },
    voterId: {
      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 execute this function if password was modified
  if (!this.isModified('password')) return next();

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

  next();
});

Here is some sample data that I am attempting to insert:

const voters = [
  {
    name: "Sherali",
    surname: "Samandarov",
    voterId: "194199",
    password: "FA654644", // will be encrypted
    isAdmin: false,
    finishedVoting: false
    // votedFor: [Object], //
  },
  {
    name: "Sherali",
    surname: "Samandarov",
    voterId: "184183",
    password: "MB454644", // will be encrypted
    isAdmin: false,
    finishedVoting: false
    // votedFor: [Object], //
  },
  {
    name: "Sherali",
    surname: "Samandarov",
    voterId: "194324",
    password: "FA651684", // will be encrypted
    isAdmin: false,
    finishedVoting: false
    // votedFor: [Object], //
  }
]

I suspect that the userSchema.pre('save', ...) logic does not trigger when using insertMany() method for some unknown reason.

Answer №1

Issue Resolved.

After implementing the suggestion provided by @victorkt, I successfully resolved the problem:

In order to ensure that the required field is set before validation, it is recommended to use pre('validate') instead of pre('save'). This allows the function to set the password field before the document is validated, as Mongoose performs validation prior to saving the document which may prevent the save middleware from being invoked in case of any validation errors.

Therefore,

userSchema.pre('validate', async function(next) {
  // Execute this function only if the password was modified
  if (!this.isModified('password')) return next();

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

  next();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Month filter functionality optimized`

I have a flirty plugin installed on my website and it's working great except for one thing: I'd like the month category to be filtered in chronological order instead of alphabetically. Is there a way to achieve this? In simpler terms, how can I ...

Creating JavaScript objects through function calls

let getBoxWidth = function() { this.width=2; }; alert(getBoxWidth.width); Hello there! Can you explain why the output is undefined in this scenario? ...

I encountered a sudden halt in functionality with my NextJs useState feature

'use client' import React, { useState } from 'react'; import Image from 'next/image'; export default function Home() { const [count,setCount] = useState<number>(0) const add = ()=> { setCount(prevCount => ...

Clickable link in popup window using fancybox

When I try to use fancybox to open an iframe and scroll to an anchor tag, it works perfectly in IE but not consistently in other browsers. It stops at a different place than the anchor. I suspect the issue may be related to JavaScript based on information ...

Tips for determining the width of an image and utilizing that measurement as the height in order to create a balanced square image

I am currently facing an issue with my code that is used to retrieve the width of an image which is set in percentages. Although I am able to obtain the width in pixels, I am struggling with correctly inserting the variable into the CSS property value usin ...

Assign characteristics to particular items within an array

When working with AngularJS/Javascript, I have an array of objects that each contain a date. My goal is to order these objects by date and then add an attribute to the last object that has a specific datetime. If there are two objects with the same date, t ...

Reloading issue with NextJs when utilizing next-i18next for translations on a specific

Having trouble with next-i18next in my app. Implemented everything correctly, but the layout keeps rerendering on pages with getStaticProps. Need to find a way to prevent this. Created a file named withStaticTranslations.ts for pages, but when trying to l ...

Discover classes dynamically and eliminate redundant div elements

I am facing an issue with a JSON request that dynamically generates search results within div elements. The search results contain duplicate classes, all starting with "lid". How can I programmatically identify and remove all but one of the duplicate class ...

Sorting subdocuments and subdocuments within subdocuments in MongoDB when extracting a document

I am looking to retrieve data from mongodb by sorting subdocuments based on their field. In my database, I have a collection called entries. Each entry represents a TvShow, with its corresponding Seasons and Episodes. Each episode contains a Mediafile. Her ...

As the window size decreases, adjust the negative left margin to increase dynamically

Is there a way to adjust the margin-left property of mydiv-2 to become increasingly negative as the browser window is scaled down horizontally? #mydiv-1{ background-color:orange; width:60%; height:400px; margin-left: 150px } #mydiv-2{ backgr ...

Combine various hierarchies using a single JSON with d3.pack

I currently have a JSON file that I need to utilize in order to create three distinct hierarchy visualizations using d3.pack. This JSON file contains data for eventA (1 or 0) and eventB (1 or 0). Each individual leaf also possesses a unique ID. The hiera ...

Exploring the world of HTML5 speed testing: getting started

Can anyone provide guidance on how to begin with an HTML5 bandwidth test? I am trying to replicate a flash-based version and any recommendations would be greatly appreciated. ...

Update to the center of the JavaScript map on Google Maps

Hello everyone, While I may not consider myself a JavaScript expert, I often piece together code snippets from various sources to get things done. Currently, I am facing a challenge with styling Google maps as they don't seem to be customizable unles ...

Unable to locate the module model in sequelize

Having some trouble setting up a basic connection between Postgres and SQL using Sequelize. I keep getting an error where I can't require the model folder, even though in this tutorial he manages to require the model folder and add it to the sync, lik ...

Process executes another process

Can anyone assist me with a JavaScript inquiry? I am curious if it is feasible to implement this: variable: { info1: 'info1', info2: 'info2', show: false, someNameFunction: functionWhichIWantRun(row) } So, after defining the var ...

Changing a div's properties is causing jQuery to behave strangely

Something strange happened while coding in javascript, especially with some jquery functions. Check out my code below <?php // Encoded in UTF-8 if(isset($_SESSION['username'])) { ?> <script type="text/javascript"> funct ...

mass editing - undesired demands or data bombardment

Lately, I've been extremely frustrated with an issue I've encountered over the past 4 days. When attempting to update multiple items within my store simultaneously, I'm experiencing a strange payload behavior. To elaborate on what I mean by ...

Unable to change the main data of slot object in VueJS

When running this demo and selecting "modify in child", the text will be updated. However, if you choose "modify top level through slot", the text remains unchanged, and attempting to click the other button afterwards will not work. Is there a way to upda ...

Attempting to eliminate any dates that have already occurred

I am faced with an array containing various dates in string format such as "2016-08-12". My goal is to eliminate any dates that have already passed by comparing them to today's date. I am using TypeScript for this task. Here is a snippet of my datoAr ...

Is it possible to simultaneously toggle buttons and submit a form?

I am currently working on a functionality that involves toggling the display of two buttons and submitting a form. Code toggleButtons() { var btn1 = document.getElementById("start"); var btn2 = document.getElementById("pause"); if (btn1.style. ...