使用Node.js快速将MongoDB数据传递到.ejs-Template

时间:2017-11-30 10:10:49

标签: javascript node.js mongodb express

我想我通过成千上万的教程点击了自己,但我仍然坚持这一点:我希望将我的express-app在开始时写入mongodb的所有数据呈现为嵌入式javascript。我想有一个简单的表格,显示来自mongodb的所有数据。在调用路由时,它也应始终获得实际数据。

我的第一个想法是,将数据保存在数组中。将它传递给.ejs文件。创建一个表,遍历我的数据数组并将其写入。我的问题是,在调用find() - Function之后,我无法将数据写入数组。

模型subscriber.js:

const mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');

var subscriberSchema = mongoose.Schema({

nr: Number,
mailIdent: {
    type: String,
    unique: true
},
from: String,
emails: {
    type: String,
    default: ''
},
text: String,
uLink: String,
anwalt: Boolean,
create_date:{
    type: Date,
    default: Date.now
}
});

subscriberSchema.plugin(uniqueValidator);

var Subscriber = module.exports = mongoose.model('Subscriber', subscriberSchema);

我对这个话题非常陌生,感觉我只是搞乱了。请帮忙

//get Subscriber
/*module.exports.getSubscribers = Subscriber.find(function(err, subs){
    if(err) return console.error(err);
    console.log(subs);
});
*/
module.exports.subscriber = Subscriber;

module.exports.getSubscriberByID = function(_id, callback){
    Subscriber.findById(_id, callback);
};
module.exports.getSubscribers = function(){
    var subscribers = Subscriber.find({});
    return subscribers;
};

然后我想将我的app.js传递给index.ejs:

app.get('/', function(req, res){
    var subs = Subscriber.getSubscribers().toArray();
    console.log(subs);
    res.render('index',{subs: subs} );
});

我知道,我的.ejs看起来仍然有点简单。但到目前为止它只是功能性的:

<!DOCTYPE html>
<html>
<head>
<link href="/assets/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<% include partials/nav.ejs %>
<h1>Welcome to the Database</h1>
<p>You won't find more Information than here!</p>
<p>Table</p>

<table>
<colgroup span="5" class="columns"></colgroup>
<tr>
    <th>Nr</th>
    <th>Name</th>
    <th>Mail</th>
    <th>uLink</th>
    <th>Anwalt</th>
</tr>
<% for (var i = 0; i<subs.length; i++) { %>
<tr>
    <td><%= subs[i].nr</td>
        <td><%= subs[i].name</td>
        <td><%= subs[i].email</td>
        <td><%= subs[i].uLink</td>
        <td><%= subs[i].anwalt</td>
        </tr>
        <% } %>
</table>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

以下是来自mongoose docs:

  

查询#ref([criteria],[callback])

     

当没有回传时,   查询未执行。执行查询时,结果将是   一系列文件。

您可以像使用getSubscriberByID函数一样使用回调,这是一个示例:

<强> subscriber.js:

...

module.exports.getSubscribers = function(cb){
    Subscriber.find({}, cb);
};

<强> app.js

app.get('/', function(req, res){
    Subscriber.getSubscribers( function (err, subs) {
        if (err) throw err;
        // else render result
        res.render('index', { subs: subs} );
    });
});

答案 1 :(得分:1)

这是您的app.js代码。

app.get('/', (req, res) => {

  //     db.collection('story').aggregate([

  //   { $lookup:
  //     {
  //       from: 'story_content',
  //       localField: 'ObjectId("5a322e1130cb6225a086f37d")',
  //       foreignField: "5a322e1130cb6225a086f37d",
  //       as: 'joinstorydata'
  //     }
  //   }
  // ]).toArray(function(err, res) {
  //   if (err) throw err;
  //   console.log("********************************************************")

  //  console.log(res);
  //  final=res;

  //   });

    db.collection('bid_placement').find().toArray((err, docs2) => {

    if (err) return console.log(err)
    // renders index.ejs

 lnames2 = [...new Set(docs2.map(a => a.bid_location))]

      lnames2.sort();

      res.render('index.ejs', {

      //story12 : docs1 ,
      //story_content: final,
      storylocation : lnames2

   });

});
});

这是您的html代码

   <select name="Courses" id="Courses">

<% for(var i=0; i<storylocation.length; i++) {%>
        <option value="<%= storylocation[i]%>"> <%= storylocation[i]%> </option>
     <% } %>

      </select>

您可以像<%= storylocation [i] .abc%>那样使用它。.在表的每一列上放置您想要的数据而不是abc ...

答案 2 :(得分:0)

这让我很生气,最后我发现了。我没有关闭.ejs文件中的Javascript。这绝对是有史以来最愚蠢的错误