Home > Net >  Unable to add object fetched from mongoDB to normal javascript array
Unable to add object fetched from mongoDB to normal javascript array

Time:10-29

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");
    }
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

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) {
    await productData.findOne({_id: data}, (err, foundBookData) => {
        // console.log(foundBookData);
        if(err){
            console.log(err);
        }
        else{
            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) => { // ...

CodePudding user response:

try to make the route callback function "async" and use "await" when calling findOne method.

  • Related