Home > OS >  How to Insert items into multiple Arrays in Node.js & MongoDB
How to Insert items into multiple Arrays in Node.js & MongoDB

Time:03-01

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

CodePudding user response:

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

CodePudding user response:

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

  • Related