Home > Blockchain >  How to use mongoose updateMany middleware to increase performance?
How to use mongoose updateMany middleware to increase performance?

Time:09-24

SOLVED: SOLUTION AT THE BOTTOM

I have the following Code where I am updating element by element:

//registerCustomers.js
const CustomerRegistrationCode = require("../models/CustomerRegistrationCode");

const setRegCodesToUsed = async (regCodes) => {
  for (let regCode of regCodes) {
    await setRegCodeToUsed(regCode._id);
  }
};

const setRegCodeToUsed = async (id) => {
  await CustomerRegistrationCode.findByIdAndUpdate(id, { used: true });
};

The Code works fine but is to slow and i want to update many (1000) CustomerRegistrationCodes at once. I had a look at the updateMany middleware function but found not much info online and on the official docs. I changed my code to the following but don't know how further.

//registerCustomers.js
const setRegCodesToUsed = async (regCodes) => {
  await CustomerRegistrationCode.updateMany(regCodes);
}
//CustomerRegistrationCode.js
CustomerRegistrationCodeSchema.pre('updateMany', async function (next, a) {
  console.log('amount arguments: ', arguments.length); //is 2
  console.log(arguments); //both parameters are functions.
  next();
});

What would be the best way to update many CustomerRegistrationCodes with 1000 different id's?

SOLUTION, thanks to Murat Colyaran

const setRegCodesToUsed = async (regCodes) => {
  const ids = [];
  regCodes.map(code => ids.push(code._id));
  await setRegCodeToUsed(ids);
};

const setRegCodeToUsed = async (ids) => {
  await CustomerRegistrationCode.updateMany(
    { _id: { $in: ids } },
    { used: true }
  );
};

CodePudding user response:

This should work:

//registerCustomers.js
const CustomerRegistrationCode = require("../models/CustomerRegistrationCode");

const setRegCodesToUsed = async (regCodes) => {
    let ids = [];
    regCodes.map((code) => ids.push(code._id.toString()));
    await setRegCodeToUsed(ids);
};

const setRegCodeToUsed = async (ids) => {
    await CustomerRegistrationCode.updateMany(
        { 
            id : { $in: ids }
        },
        {
            used: true
        }
    );
};

Instead of sending a query for every records, we just parse the id and send a bulk request with $in

  • Related