我想我点击了自己浏览了数千个教程,但我仍然卡在这一点上:我想渲染所有数据,我的express-app在开始时写入mongodb,嵌入javascript。我想要一个简单的表来显示来自 mongodb 的所有数据。在调用路由时,它也应始终获取实际的数据。
我的第一个想法是,将数据保存在数组中。将其传递给 .ejs 文件。创建一个表,迭代我的数据数组并将其写入。我的问题是,在调用 find() 函数后我无法将数据写入数组。
模型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>
最佳答案
以下内容来自 Mongoose 文档:
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.
您可以像使用 getSubscriberByID
函数一样使用回调,下面是一个示例:
订阅者.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} );
});
});
关于javascript - 使用 Node.js Express 将 MongoDB 数据传递到 .ejs-Template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47570825/