Home > front end >  Loop through array and add data
Loop through array and add data

Time:10-06

I have an array called "content". In this array is the "asin-id" (It's a kind of product ID). I'm trying to loop through the content array and get from the asin-id the specific product so I can add the product to the array and save the new content-array in the db.

Something is wrong. I don't know how to do it.

Expected result:

content: [{ asin: "asin-ID", product: product }, ...]

What I tried:

exports.createBlogPost = async (req, res) => {
    try {
        const content = req.body.content

        content.map(async (element) => {
            const asin = element.asin
            const product = await Product.findOne({ asin: asin })
            element.product = product
            return element
        })

        console.log(content)
    

        const post = new BlogPost({
            postTitle: req.body.postTitle,
            postQuery: req.body.postQuery,
            content: content,
            mainImage: req.file
        })
        console.log("Saved: "   post)
        await post.save()

        if(post) {
            return res.status(200).json({
                success: true,
                message: 'Saved blog post successfully',
                post: post
            })
        }
    } catch(err) {
        console.log(err)
    }
}

CodePudding user response:

I think the problem may be simply that you're using map without assigning the result to a variable. Try replacing your code with something similar to the following:

let updatedContent = content.map(async (element) => {
        const asin = element.asin
        const product = await Product.findOne({ asin: asin })
        element.product = product
        return element
 })

 console.log(updatedContent)
  • Related