NodeJS、MongoDB:传递获取的数据并将其显示在 HTML 上 [英] NodeJS, MongoDB : Pass fetched data and display it on HTML

查看:45
本文介绍了NodeJS、MongoDB:传递获取的数据并将其显示在 HTML 上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的代码来从 mongodb 获取数据:

I have written below code to get data from mongodb :

app.get('/StudentQuestionsPage',function(req,res){
    var questions="";
    MongoClient.connect(url, function (err, db) {
    if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
    } 
    else {
    console.log('Connection established to', url);  
    var collection = db.collection('studentQuestions');
    var cursor =collection.find();  

    fs.readFile( __dirname + '/StudentQuestionsPage.html', 'utf8', function(err, content) {
      var result = content;
      cursor.each(function (err, doc) {
      if (err) {
        console.log(err);
      } else {
        result +=doc;
      }
        }); 
        res.send(result);
            });
        }
    });
});

我想将超过 1 个的问题传递给 html 文件,并想在那里显示这些问题.我可以看到正在提取问题,但我不确定如何在 HTML 上显示它们.
有人可以帮忙吗?

I want to pass the questions which is more than 1 to html file and want to show those questions there. I can see the questions are being fetched but I am not sure how I can display them on HTML.
can someone help?

我添加了以下代码:

I have added below code :

app.get('/StudentQuestionsPage',function(req,res){  
var studentQuestions = mongoose.model('studentQuestion', studentQuestionSchema);

fs.readFile( __dirname + '/StudentQuestionsPage.html', 'utf8', function(err, content) {
    var result = content;  
    res.send(result).status({studentQuestions:studentQuestions});
    mongoose.connection.close()
    });
});

但它不会在 HTML 上打印值.下面是屏幕截图.

But it does not print values on HTML. Below is the screenshot.

请告诉我如何继续.抱歉打了很多次.

Please let me know how to proceed. Sorry for pinging a lot.

推荐答案

var questions = [
    { number: '1', text: 'question_1' },
    { number: '2', text: 'question_2' },
    { number: '3', text: 'question_3' },
];

res.send(result, {
    questions: questions});

在上面的代码中,我假设我有一个预先定义的问题数组,而不是初始化一个空数组.在代码的 res.send() 部分,添加我上面写的代码,这是为了创建一个问题列表,我们将在 html 文件中使用它来显示问题.HTML 文件 -

In the code above instead of initializing an empty array, I am assuming that I have a pre defined array of questions. In the res.send() part of the code, add the code that I have written above this is to create a list of questions which we will use in the html file to display the questions. HTML file -

<h2>Questions</h2>
<ul>
<% questions.forEach(function(question) { %>
    <li>Number: <%= question.number %> - Text: <%= question.text %></li>
<% }); %>
</ul>

通过这种方式您可以显示问题列表,但这里我们已经预先定义了数组.您需要做的是,您需要从 MongoDb 中获取数据,而不是自己将数据传递给数组.您需要做的就是根据您数据库的字段更改字段名称.

This way you can display the list of questions but here we have pre-defined the array. What you need to do is that instead of passing the data to the array yourself, you need to get it from the MongoDb. All you will need to do is change the field names according to the fields of you Database.

编辑丢弃硬编码的问题数组.我现在将尝试从 mongodb 中获取数据.我希望你有 mongoDb 设置并且一切顺利.在不同的终端打开mongod和mongo,然后运行代码..

EDIT Discard the hardcoded questions array. I will now try to fetch data from the mongodb now. I hope you have mongoDb setup and good to go. Open mongod and mongo in different terminals and then run the code..

在 server.js 文件中

In server.js file

var mongoose = require('mongoose');//I am using mongoose which you can get by running sudo npm install mongoose
mongoose.connect('mongodb://localhost:27017/dbName');//dbName is the database name from which you need to import the questions

这样你就可以在你的节点应用程序中触发一个数据库.然后你需要定义你的问题"数据集.

This way you can fire a db in your node app. Then you need to define your 'Question' dataset.

question.js 文件

question.js file

var mongoose = require('mongoose');
module.exports = mongoose.model('Question', {
number: String,
text: String
}

希望这有帮助!!!

这篇关于NodeJS、MongoDB:传递获取的数据并将其显示在 HTML 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆