Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

node.js - NodeJS, MongoDB : Pass fetched data and display it on HTML

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

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

But it does not print values on HTML. Below is the screenshot.enter image description here

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
var questions = [
    { number: '1', text: 'question_1' },
    { number: '2', text: 'question_2' },
    { number: '3', text: 'question_3' },
];

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

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>

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.

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

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 file

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

Hope this helps!!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...