alvarosps
alvarosps

Reputation: 83

NodeJS retrieve multiple data from MongoDB and display on Jade(Pug)

I have some MongoDB collections, and need to display them in my site, making it a dynamic page(it's the team members, if 1 is removed or added, it should refresh on the page)

my collections is like(mongodb terminal):

db.capitao.find() = { "_id" : ObjectId("59a6b67519404d41f9988524"), "nome" : "Renato", "email" : "[email protected]
om", "imagem" : "renato.png", "curso" : "Engenharia Mecânica", "lider" : 1 }

db.chassi.find() = { 
{ "_id" : ObjectId("59a6b69f19404d41f9988529"), "nome" : "Carlos", "email" : "[email protected]
", "imagem" : "possebon.png", "curso" : "Engenharia Mecânica", "lider" : 1 }
{ "_id" : ObjectId("59a6b69f19404d41f998852a"), "nome" : "Felipe", "email" : "example@gmai
l.com", "imagem" : "brunetto.png", "curso" : "Engenharia Mecânica", "lider" : 0 }
{ "_id" : ObjectId("59a6b69f19404d41f998852b"), "nome" : "Isabelle", "email" : "example@
gmail.com", "imagem" : "isabelle.png", "curso" : "Engenharia Mecânica", "lider" : 0 }
{ "_id" : ObjectId("59a6b69f19404d41f998852c"), "nome" : "Mateus Dandolini Pescador", "email" : "[email protected]
r", "imagem" : "pescador.png", "curso" : "Engenharia Mecânica", "lider" : 0 }
{ "_id" : ObjectId("59a6b69f19404d41f998852d"), "nome" : "Marcelino Colla Junior", "email" : "[email protected]",
 "imagem" : "marcelino.png", "curso" : "Engenharia Mecânica", "lider" : 0 }

my index.js(only trying to retrieve from "capitao" first):

router.get('/', function(req, res,next) {
   var resultArray = {
                      capitao : [],
                      chassi : []
                     };

    var db = req.db;

    //var collectionCapitao = db.collection('capitao').find();

    var collectionCapitao = db.get('capitao');

    //var chassi = db.collection('chassi').find();

    collectionCapitao.find({},{},function(e,docs){
        res.render('index', {
            env: env,
            capitao: collectionCapitao
        });
    });
});

and my index.jade:

            .row
                each membro, i in capitao
                    .col-sm-4
                        .team-member
                            img.mx-auto.rounded-circle(src='/img/team/#{membro.imagem}', alt='#{membro.nome}')
                            h4 membro.nome
                            p.text-muted membro.curso
                            ul.list-inline.social-buttons
                                li.list-inline-item
                                    a(href="mailto:#{membro.email}")
                                        i.fa.fa-envelope

my problems:

Upvotes: 1

Views: 930

Answers (3)

Jeremy Thille
Jeremy Thille

Reputation: 26360

I have just rewritten the solution you have posted (glad it works :) because you repeat yourself a LOT (10 times the same function!)

So here's the DRY version (Don't Repeat Yourself). Disclaimer : this is untested code!

router.get('/', function (req, res, next) {

    const db = req.db;
    const async = require("async")

    const names = ['capitao','aerodinamica','chassi','controles','drivetrain','eletronica','gestao','marketing','powertrain','suspensao']

    const collections = names.map(name => db.get(name) )

    const functions = collections.map(collection => {
        return done => collection.find( {}, done )
    })

    async.series( functions, (err, results) => {
        // "results" is now an array containing [ docs1, docs2, .. ]
        res.render('index', {
            env: env,
            capitao: results[0],
            aerodinamica: results[1],
            chassi: results[2],
            controles: results[3],
            drivetrain: results[4],
            eletronica: results[5],
            gestao: results[6],
            marketing: results[7],
            powertrain: results[8],
            suspensao: results[9]
        });
    })
});

Upvotes: 1

alvarosps
alvarosps

Reputation: 83

here's the code now, solved

router.get('/', function(req, res,next) {

    var db = req.db;


    var collectionCapitao = db.get('capitao');
    var collectionAerodinamica = db.get('aerodinamica');
    var collectionChassi = db.get('chassi');
    var collectionControles = db.get('controles');
    var collectionDrivetrain = db.get('drivetrain');
    var collectionEletronica = db.get('eletronica');
    var collectionGestao = db.get('gestao');
    var collectionMarketing = db.get('marketing');
    var collectionPowertrain = db.get('powertrain');
    var collectionSuspensao = db.get('suspensao');


    const async = require("async")

    const getCapitao = done => {
         collectionCapitao.find({}, (err,docs) => {
              done(err, docs)
         })
    }

    const getAerodinamica = done => {
         collectionAerodinamica.find({}, (err,docs) => {
              done(err, docs)
         })
    }

    const getChassi = done => {
         collectionChassi.find({}, (err,docs) => {
              done(err, docs)
         })
    }

    const getControles = done => {
         collectionControles.find({}, (err,docs) => {
              done(err, docs)
         })
    }

    const getDrivetrain = done => {
         collectionDrivetrain.find({}, (err,docs) => {
              done(err, docs)
         })
    }

    const getEletronica = done => {
         collectionEletronica.find({}, (err,docs) => {
              done(err, docs)
         })
    }

    const getGestao = done => {
         collectionGestao.find({}, (err,docs) => {
              done(err, docs)
         })
    }

    const getMarketing = done => {
         collectionMarketing.find({}, (err,docs) => {
              done(err, docs)
         })
    }

    const getPowertrain = done => {
         collectionPowertrain.find({}, (err,docs) => {
              done(err, docs)
         })
    }

    const getSuspensao = done => {
         collectionSuspensao.find({}, (err,docs) => {
              done(err, docs)
         })
    }

    async.series([
        done => getCapitao(done),
        done => getAerodinamica(done),
        done => getChassi(done),
        done => getControles(done),
        done => getDrivetrain(done),
        done => getEletronica(done),
        done => getGestao(done),
        done => getMarketing(done),
        done => getPowertrain(done),
        done => getSuspensao(done),
    ], (err, results) => {
        // "results" is now an array containing [ docs1, docs2, .. ]
        res.render('index', {
            env: env,
            capitao: results[0],
            aerodinamica : results[1],
            chassi : results[2],
            controles : results[3],
            drivetrain : results[4], 
            eletronica : results[5],
            gestao : results[6],
            marketing : results[7], 
            powertrain : results[8],
            suspensao : results[9]
        });
    })
});

Upvotes: 0

Jeremy Thille
Jeremy Thille

Reputation: 26360

It looks like you have to make multiple calls to your database and wait for all the results, then pass all these results together to your template. Here's how to do it with AsyncJS :

const async = require("async")

async.series([
    done => collectionCapitao.find({}, done),
    done => collectionChassi.find({}, done)
], (err, results) => {
    // "results" is now an array containing [ docs1, docs2 ]
    res.render('index', {
        env: env,
        capitao: results[0],
        chassi : results[1]
    });
})

Since this code is quite minimal and concise, here's a slightly more detailed version so you understand better what's going on :

const getCapitao = done => {
     collectionCapitao.find({}, (err,docs) => {
          done(err, docs)
     })
}

const getChassi = done => {
     collectionChassi.find({}, (err,docs) => {
          done(err, docs)
     })
}

async.series([
    done => getCapitao(done),
    done => getChassi(done)
], ...... // get both results here

Upvotes: 0

Related Questions