NodeJS从MongoDB中检索多个数据并在Jade(Pug)上显示

时间:2017-08-30 14:43:09

标签: javascript node.js mongodb express pug

我有一些MongoDB集合,需要在我的网站上显示它们,使其成为一个动态页面(这是团队成员,如果删除或添加1,它应该在页面上刷新)

我的收藏品就像( mongodb终端):

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

db.chassi.find() = { 
{ "_id" : ObjectId("59a6b69f19404d41f9988529"), "nome" : "Carlos", "email" : "example@ufrgs.br
", "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" : "example@ufrgs.b
r", "imagem" : "pescador.png", "curso" : "Engenharia Mecânica", "lider" : 0 }
{ "_id" : ObjectId("59a6b69f19404d41f998852d"), "nome" : "Marcelino Colla Junior", "email" : "junior_colla@hotmail.com",
 "imagem" : "marcelino.png", "curso" : "Engenharia Mecânica", "lider" : 0 }

我的index.js(首先尝试从“capitao”中检索):

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
        });
    });
});

和我的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

我的问题:

  • 所有属性在jade中返回undefined(已解决)
  • “capitao”只有1条记录,但它在Jade中产生了31条记录(已解决)
  • 如何在index.js中获取MULTIPLE集合并将它们发送给Jade?

3 个答案:

答案 0 :(得分:0)

看起来您必须多次调用数据库并等待所有结果,然后将所有这些结果一起传递给您的模板。以下是使用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]
    });
})

由于此代码非常简洁,所以这里有一个稍微详细的版本,因此您可以更好地理解正在发生的事情:

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

答案 1 :(得分:0)

这是现在的代码,解决了

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]
        });
    })
});

答案 2 :(得分:0)

我刚刚重写了你发布的解决方案(很高兴它有效:)因为你重复自己很多(相同功能的10倍!)

所以这里是DRY版本(不要重复自己)。 免责声明:这是未经测试的代码!

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]
        });
    })
});