Home > Back-end >  how do correct loop in loop
how do correct loop in loop

Time:12-16

hi I try to do loop of array inside loop of array but the result I get is now whet I want I have one array of books id and one array of quantity now whet I try is foreach book in the quantity field decrease by the value in the array quantity but whet I get is take all the quantity array sum all the values and decrease from every book

booksId = ['63761881ec1e2022c0d9e987','637e262ea6fd0c1c544e9a19','637a2798b661e13c40433698']
quantity = [ '1', '2', '1' ]

const updateQuantityBooks = async (booksId, quantity) => {
    quantity.map(async (que, i) => {
        booksId.map(async (el, i) => {
            await Book.findByIdAndUpdate(el, { $inc: { quantity: -que } }, {
                new: true,
                runValidators: true
            })
        })
    })
}

now whet happen is decrease foreach book 4 in the quantity

CodePudding user response:

The code is logically incorrect. What your code does is decrease [1,2,1] from each book in 3 steps. The 2nd loop is decreasing quantity by [1,2,1] from each book.

What I am assuming is that you want to reduce the quantity in the same sequence i.e. 1 from 1st book, 2 from 2nd and 1 from 3rd and so on as per your quantity array.

For that, you need to make sure both arrays are of same length and are in correct sequence. And then you can simply use index of quantity array in a single loop. Sample code for this :

booksId = ['63761881ec1e2022c0d9e987','637e262ea6fd0c1c544e9a19','637a2798b661e13c40433698']
quantity = [ '1', '2', '1' ]
const updateQuantityBooks = async (booksId, quantity) => {
    booksId.map(async (el, i) => {
        await Book.findByIdAndUpdate(el, { $inc: { quantity: -quantity[i]} }, {
            new: true,
            runValidators: true
        })
    })
}
  • Related