通过Express将mongodb数据传递到视图中

时间:2019-01-05 15:29:24

标签: node.js mongodb express ejs

我正在构建一个非常基本的应用程序来预订要租用的车辆,我试图从mongodb访问数据,因为它在加载时输出到控制台,这似乎行得通。我无法在我的视图中呈现此信息。如果在功能范围之外设置了render方法,则无法访问db数据;如果在内部设置了render,则预订页面将永远不会加载。几天来,我一直在弄乱相同的代码块,但我并不高兴。

//------------------------------------------------THE SET UP--------------------------------------------
// set node dependencies
let express = require("express");
let bodyParser = require("body-parser");
let mongoose = require("mongoose");
let connection = mongoose.connection;

let data = mongoose.connect("mongodb://localhost:27017/test")


// allow for encoding od POST DATA
let urlencodedParser = bodyParser.urlencoded({extended: false});

// set up app to extend express
let app = express();

// view engine
app.set("view engine", "ejs");

// static files
app.use("/assets", express.static("assets"));
//------------------------------------------------------------------------------------------------------

// REDIRECTS BASED ON URL
app.get('/', function(req,res){
    res.render("index")
});

app.get('/booking', function(req,res){
    res.render("booking",{qs:req.query})
});
app.post('/booking',urlencodedParser, function(req,res){
    // Surround this with if !blacklisted to run inner code
    if (req.body.blacklist !== "on"){
        console.log(req.body);

//预订页面包含了年龄的详细信息并相应地重定向/查询数据库

        if (req.body.age >= 25){

            connection.once('open', function () {

                connection.db.collection("vehicles", function(err, collection){
                    collection.find({}).toArray(function(err, data){
                        console.log(data[0]._id); // it will print collection data
                    })
                });
                res.render("contact-success",{data:req.body})
                connection.close();
            });
        }
        else if (req.body.age < 25 && req.body.age > 17){

            connection.once('open', function () {

                connection.db.collection("vehicles", function(err, collection){
                    collection.find({}).toArray(function(err, data){
                        console.log(data[0]._id + "<25 message"); // it will print collection data
                    })
                })
            })

// THIS IS WHERE I WANT TO PASS THE DB DATA INTO.. so that it redirects to this page and filters the vehicles collection appropriately.

            res.render("contact-failed",{data:req.body});
        }
    }
    else{
        console.log(req.body.firstName , req.body.lastName , "Has been blacklisted!")
        res.render("blacklisted",{data:req.body}); 
    }
    // else if blacklisted redirect to a sorry, contact company page.
});

let port = 3000;

app.listen(port);
console.log("listening on port " + port);

1 个答案:

答案 0 :(得分:0)

关于代码的几件事-

  1. 您应该在对res.render()的调用内致电mongodb

    connection.once('open', function () {
    
        connection.db.collection("vehicles", function(err, collection){
            collection.find({}).toArray(function(err, data){
                console.log(data[0]._id); // it will print collection data
                res.render("contact-success",{data:req.body})
            });
        });
    
        connection.close();
    });
    
  2. 您不检查错误。如果您在查询中遇到任何错误,最终将对请求没有任何响应。因此,检查错误总是更好。

    if(err) {
        // process the error and send appropriate message.
    } else {
        // send what you want to send to view.
        res.render("contact-success",{data:req.body})
    }  
    
  3. 您有条件

    if (req.body.age >= 25){
    ...
    } else if (req.body.age < 25 && req.body.age > 17){
    ...
    }
    

    但是别无其他。因此,如果两个条件中的任何一个都不满足,您最终将对请求没有任何响应。

  4. 每个条件中应有一个res.render()res.send()