How to use data from a query in mongoDB? [duplicate]

2

I want to use the data that is returned from 'find ()' from MongoDB to create a table using the array that returns from MongoDB, and after the table is ready, generate a PDF, but I can not get access to the result data outside the connection function with the DB.

   db.open( function (err, mongoclient) {
    mongoclient.collection('postagens', function (err, collection) {
        collection.find().toArray(function(err, results){
            if(err){
                res.json(err);
            } else {
                res.send(results);
            }
            mongoclient.close();
            return results
        })

    })
})

let conteudoPDF = {
    content:[
        {text: 'Teste de PDF', style: 'header'},
        'Teste com pdfMake',
        {
            table:{
                body:[
                    [ 'Id Usuário', 'Id Post', 'Título', 'Texto'],
                   /*Aqui irá o forEach para gerar a tabela*/

                ]
            }
        }
    ]
}

The variable 'results' contains the array with the JSON that I need, and I want to have access to this data outside the connection function with the DB, and 'return' is not exporting this data out of the function

    
asked by anonymous 27.07.2017 / 15:41

1 answer

1

You can fill in the PDF content by invoking a function for this in the query success , like this:

 db.open(function(err, mongoclient) {
    mongoclient.collection('postagens', function(err, collection) {
        collection.find().toArray(function(err, results) {
            if (err) {
                res.json(err);
            } else {
                // invocar a função que preenche o pdf aqui
                preencherPDF(results);
                res.send(results);
            }
            mongoclient.close();
            return results
        })

    })
})

function preencherPDF(conteudo) {
    let conteudoPDF = {
        content: [{
                text: 'Teste de PDF',
                style: 'header'
            },
            'Teste com pdfMake',
            {
                table: {
                    body: [
                        ['Id Usuário', 'Id Post', 'Título', 'Texto'],
                        /*Aqui irá o forEach para gerar a tabela*/
                        conteudo.forEach((item) => {
                            console.log(item)
                        });
                    ]
                }
            }
        ]
    }
}
    
27.07.2017 / 15:45