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

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

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 Relatório

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 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