简体   繁体   中英

Passing MongoDB Data into .ejs-Template with Node.js Express

I think i clicked myself through thousands of tutorials but i'm still stucked at this point: I want to render all the data, which my express-app is writing into mongodb at its start, into embedded javascript. I would like to have a simple table which is showing all the data from mongodb. It shall also always get the actualized Data when calling the route.

My first idea was, to save the data in an array. Pass it to the .ejs file. Create a table, iterate through my data-array and write it in. My problem is, that i can not write the data into an array after calling the find()-Function.

The model 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);

I'm really new to the topic and it feels like i'm just messing around. Please help

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

Then i want to pass it with my app.js to the index.ejs:

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

I know, that my .ejs still seems a little simple. But so far it shall be just functional:

<!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>

The following is from mongoose docs:

Query#find([criteria], [callback])

When no callback is passed, the query is not executed. When the query is executed, the result will be an array of documents.

You can use a callback just Like you do with getSubscriberByID function, here is an example:

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

here is ur app.js code..

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

   });

});
});

and here is ur html code

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

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

      </select>

you can use it like <%= storylocation[i].abc%> .. put you desire data instead of abc on each column of table...

It was driving me mad and finally i found out. I did not closed the Javascript in the .ejs file. That was definetly the most stupid misstake ever

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM