1

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)
    }
}
3
  • "Something is wrong" isn't sufficient for explaining your error... You should be as specific as possible, especially pertaining to the actual error occurring, so that we can help. Commented Oct 5, 2021 at 14:10
  • The problem is I don‘t get the product in the content array. Commented Oct 5, 2021 at 14:16
  • I see. You're not actually getting an error... The values just aren't being populated as expected. I think I see the issue. I posted an answer that should help. Commented Oct 5, 2021 at 15:16

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.