Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda