Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda