Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!