I am using MongoDB and Mongoose + Node.js QUESTION: I have to display the data f
ID: 3915124 • Letter: I
Question
I am using MongoDB and Mongoose + Node.js
QUESTION: I have to display the data from the getData Function. How will I display the table on a Webpage?
********************************************
CLASS: mainController.js
const Post = require('../models/flat.file')
const mongoose = require('mongoose');
const path = require('path');
var str = "";
module.exports = {
showHome: showHome,
getData: getData
}
//function to display homepage
function showHome(req, res) {
res.sendFile(path.resolve(__dirname + '../../public/index.html'));
/*server.get('/', function(req,res) //display str from index?
{
res.render('index',{
test: str
});
});*/
}
function getData(req, res) {
var db = mongoose.connection;
/*var resp=db.collection("flatfiles").find({}).toArray(function (err,result){
if(err){
throw err;
}
resp.each(function(error,item){
if(error){
throw error;
}
if(item!=null){
str=str+" ID: "+item.objectid+" Settlement ID: "+item['settlement-id']+"</br>";
}
})
console.log(str);
});*/
var cursor = db.collection('flatfiles').find();
//noinspection JSDeprecatedSymbols
if (cursor != null) {
cursor.forEach(function(err, item) {
if (item != null) {
str = str + " Employee id " + item.Employeeid + "</br>";
}
if(err){
throw "Error"+err;
}
});
res.send(str);
db.close();
}
}
CLASS: server.js
const express = require('express'),
app = express(),
port = process.env.PORT || 8080,
mongoose = require('mongoose');
app.use(express.static(__dirname + '/public'));
//connect to db
mongoose.connect("mongodb://localhost:27017/testing");
app.use(require('./app/routes'))
/*var x=function(app) {
app.use('./app/routes');
};*/
app.listen(port, () => {
console.log('App Listening on http://localhost:${port}');
})
CLASS: index.html
<html>
<head>
<title>Sample Table Display</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--<script src="../server.js"></script>-->
</head>
<body>
<script>
$(document).ready(function() {
$("#sampleButton").click(function() {
$.ajax({
url: "/data",
type: 'GET',
success: function(result) {
$("#div1").html(result);
}
});
});
});
</script>
<div>
<button id="sampleButton">Done</button>
</div>
<div id="div1"></div>
<%= test %>
</body>
</html>
Explanation / Answer
save the file with .html extenstion and then open it to run.it will execute and get the ouput in browser.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.