Ad
ForEach How Save Multi Data Into MondoDB
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
Related Questions
- → How do I create an array from a single form input box with php on octobercms?
- → Print the output value of an array in twig [OctoberCMS]
- → Declare an array variable to the controller/component [Laravel, October CMS]
- → Removing a JavaScript property inside a specific Object within an Array
- → Javascript loop indexing issue
- → search array without duplicates React.js
- → Populating array with items from different HTML attributes
- → Get all index value of 1 from binary "01000111"
- → Remove objects from array - Two different approaches, two different results when consulting the length of each array
- → Compare values in two arrays
- → adding multiple polygons in google maps using loops and arrays
- → .split() JS not "splitting" correctly?
- → Vue.js - Binding radio elements of same name to array
Ad