Rendering view after multiple SELECT queries in Express

后端 未结 2 486
遥遥无期
遥遥无期 2020-12-28 10:48

I\'m a bit new in Node.JS and Express framework and I have a great problem with the code below:

app.get(\'/student\', function(req, res) {
    var dbRequest          


        
2条回答
  •  没有蜡笔的小新
    2020-12-28 11:16

    I know this is an old question, but for anybody still having problems and using MongoDB instead this is what worked for me.

    //index.js    
    const express = require('express');
    const router = express.Router();
    
    function getData (req, res, next) {
      var db = req.db;
      var collection = db.get('usercollection');
    
      collection.find({}, {}, function(e, docs) {
        req.data = docs;
        return next();
      });
    }
    
    function getVendor (req, res, next) {
      var db = req.db;
      var collection = db.get('usercollection');
    
      collection.distinct("vendor", function(e, docs) {
        req.vendor = docs
        next();
      });
    }
    
    function getType (req, res, next) {
      var db = req.db;
      var collection = db.get('usercollection');
    
      collection.distinct("type", function(e, docs) {
        req.type = docs
        next();
      });
    }
    
    function renderData(req, res) {
        res.render('index', {
            data: req.data,
            vendor: req.vendor,
            type: req.type
        });
    }
    
    /* GET home page. */
    router.get('/', getData, getVendor, getType, renderData);
    
    
    module.exports = router;
    

    Then inside your ejs file

    //index.ejs 
    
    

    Choose a Vendor

提交回复
热议问题