[Solved] NodeJS, MongoDB : Pass fetched data and display it on HTML


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

3

solved NodeJS, MongoDB : Pass fetched data and display it on HTML