Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
Unable to add object fetched from mongoDB to normal javascript array

I am trying to create an add to cart button which fetches the data from product database using the id of specific product which I selected. I am trying to push the object found using the same Id into a normal javascript array and then to display it using ejs methods. While I was tring I found I am unable to push the data in object form.

Summary:

On 7th line I have declared an array and in that array I want to store some objects which I have fetched frome a db model. On 15th line I am trying to push the object form into my array so that I could iterate through the objects to display them on my page using ejs. But I am unable to do that.

screenshots:

  1. Here's the final result I'm getting even after trying to push objects in array:

empty array logged

  1. Here are the objects I'm trying to push:

Objects

Code:

app.get("/cart", (req, res) => {
    if (req.isAuthenticated()) {
        const findcartdata = req.user.username;
        userData.findOne({email: findcartdata}, (err, BookId) => {
            // console.log(BookId.cartItemId);
            const idArray = BookId.cartItemId;
            var bookArray = [];
            idArray.forEach((data) => {
                productData.findOne({_id: data}, (err, foundBookData) =>{
                    // console.log(foundBookData);
                    if(err){
                        console.log(err);
                    }
                    else{
                        bookArray.push(foundBookData);
                    }
                })
            });
            console.log(bookArray);
            // res.render("cart", {
            //     cartBookArray: BookId.cartItemId
            // })
        });
    } else {
        res.redirect("/login");
    }
})

In above code i found the user's email using passport authentication user method and using that email I wanted to add the products in a different javascript array (which I am goint to pass to my ejs file of cart and then iterate it on list) using those array of Id which I got from another model called userData. The problem is I am able to find userData of each Id but unable to store them as an array of objects.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Looks like a timing issue, your code completes before the database downloads the objects and pushes them to your array.

This should fix your issue:

// ...
const idArray = BookId.cartItemId;
var bookArray = [];
for (const data of idArray) {
    const foundBookData = await productData.findOne({_id: data}).catch(console.error);
    if (!foundBookData) continue;
    bookArray.push(foundBookData);
}

console.log(bookArray);
// ...

By the way, make sure to make the whole function asynchronous as well, which would be done by changing this line:

userData.findOne({email: findcartdata}, async (err, BookId) => { // ...
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!