Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

65
Views
Missing updated record when using map function

This is my code for update many records with mongodb.

const nfts = await waxModel.find();
console.log(nfts.length) // -> 121

// Option 1: using map()
nfts.map(async nft => {
    nft.trait_attribute = null;
    await nft.save();
  });

// Option 2: using loop
for (let i = 0; i < nfts.length; i++) {
    nfts[i].trait_attribute = null;
    await nfts[i].save();
  }
  • This is my DB, no recored have trait_attribute: null:

enter image description here

  • This is the first result when I use map(), only have 2 records:

enter image description here

  • And this is the second result when I use for loop:

enter image description here

I don't know that is the problem. In my previous question: I know map methods don't handle the asynchronous function but it's still have full records not missing many updated records as now. Thank for your attention.

8 months ago · Juan Pablo Isaza
1 answers
Answer question

0

It looks like your code doesn't handle race conditions well.

The first option saves every nft simultaneously whilst the second one saves them one at a time. A more readable way to do that would be using a for-of loop:

for (const nft of nfts) {
  nft.trait_attribute = null;
  await nft.save();
}
8 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs