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

189
Vistas
How to Insert items into multiple Arrays in Node.js & MongoDB

This might be a weird question but I believe nothing is completely impossible.

I have a List of Users in MongoDB, each user has among other things, properties array which is currently empty.

In Excel sheet, I have a data that represents each user's properties which I want to programmatically insert in each user's properties array.

Importing excel sheet is fast and easy to populating each user's properties is what gives me the problem.

I have added userId, and PropeId, from the users and the properties they bought, so Identify them as seen below Assignment table

router.put('/importdata', async (req, res)=>{
// upload queries
const imported = req.files.importdata;
 const uploadpath = path.resolve(`public/excel_maneger/uploads/ ${imported.name}`);
if (imported.truncated) {
  throw new Error("Uploaded File is too big, should not be morethan 20 MB");
}
await imported.mv(uploadpath);
 const file = render.readFile(uploadpath);
  const sheets = file.SheetNames;
  const data = [];
  for (let i = 0; i < sheets.length; i++) {
    const sheetname = sheets[i];
    const sheetData = render.utils.sheet_to_json(file.Sheets[sheetname]);
    sheetData.forEach((item) => {
      data.push(item);
    });
  }

 try {
   const users = await User.find({role: 'Customer'})   
       for(let i = 0; i < users.length; i++ ){
            data.forEach((d) => {
               if(users[i].id == d.id){
                 User.updateMany(
                   {},
                   {
                     $set: {
                       properties: {
                         propeId: d.propeId,
                       },
                     },
                   },
                   (err, d) => {
                     if (err) console.log(err);
                   }
                 );
               }
            });
       }
          
        


 } catch (err) {
   console.log(err)
 }
  
})

The Problem is that this code updates everyone on the Database (including non specified users) with the same information, Please I need help, I am trying to import 11 thousand users information from excel to database

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I have finally figured where I made the mistake, I am supposed to use $in: operator to access multiple Ids as desired.

Here's the solution:

  data.forEach((d) => {
      User.updateMany(
        { _id: { $in: [d.id] } },
        {
          $push: {
            properties: d.propeId,
          },
        },
        (err, d) => {
          if (err) return false;
        }
      );
    });

Above solved the problem amazingly

about 4 years ago · Juan Pablo Isaza Denunciar

0

When you are updating your User.updateMany(), You are not passing in the Id.

What it does is it when if statement is true, it updates all the user, You can use findByIdAndUpdate

Also you should be using async/await. Since that is what you are using to find the user

await User.findByIdAndUpdate( users[i]._id,{ $set: { properties: { propeId: d.propeId }}})
about 4 years ago · Juan Pablo Isaza 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