Ad

ForEach How Save Multi Data Into MondoDB

- 1 answer

I have a application based on Stripe and MERN stack. My issue is that when I hit endpoint to fetch charges then console.log the result I see an array of charges. Which is good. So I decided to use forEach to iterate over them and extract amount value. This works.

But..

router.get('/all', (req, res) => {
    stripe.charges.list({
        limit: 3
    }).then(charges => {
        charges.data.forEach(charge => {
            return newData = new Charge({
                amount: charge.amount,
            })
        });
        newData
            .save()
            .then(charge => {
                res.json(charge)
            })
            .catch(err => console.log(err))
    })
})

When I using forEach to create a record in MongoDB based on my model I only get one record saved in the DB even if I have at least 3 charges in the array. How do I fix that?

thanks

Ad

Answer

You'd better use one operation instead of multi. For this: Model.insertMany method. https://mongoosejs.com/docs/api.html#model_Model.insertMany

Pseudo-code:

const dataForSaving = charges.data.map((charge) => {
  return {
    amount: charge.amount,
  };
});

Collection.insertMany(dataForSaving, (err, docs) => {
  if (err) {
    throw new Error(err);
  }

  console.log(docs);
});
Ad
source: stackoverflow.com
Ad