I am trying to learn how to get data that is already stored in MongoDB and display it as a table in HTML. I've never worked with HTML or JavaScript much so I decided to start by creating a script within my HTML code and display a simple table using a loop:
<div>
<script>
var words = ["One", "Two", "Three", "Four", "Five", "Six", "Seven"];
var numbers = [1,2,3,4,5,6,7];
document.write('<table>');
for (var i =0; i < words.length; i++){
document.write('<tbody><tr><td>' + words[i] + '</td>' + '<td>' + numbers[i] + '</td></tr></tbody>' );
}
document.write('</table>');
</script>
</div>
The output I got was:
One 1
Two 2
Three 3
Four 4
Five 5
Six 6
Seven 7
Now that I figured out how the syntax works, I would like to use something like NodeJS/ExpressJS/Mongoose to get documents from MongoDB and store them into an array and display them as a table.
My MongoDB Schema that already exists inside db test
and collection test1
is:
{
"_id": ObjectId("fffffffffffffff"),
"Words": "One",
"Numbers": 1
}
{
"_id": ObjectId("aaaaaaaaaaaaaaa"),
"Words": "Two",
"Numbers": 2
}
...
I would like to query and store the values of "Words" and "Numbers" from the documents into arrays wordArray
and numArray
and display them as a table.
I found these related questions:
Displaying MongoDB Documents with HTML
Display MongoDB values in HTML
How to use HTML in Express framework with nunjucks- no jade
How would I go about doing what I want? Which one of those links should I look at? Because I'm very lost and don't know where to start. Is there an easy way to do this? I tried doing the following:
<script>
//import express package
var express = require("express");
//import mongodb package
var mongodb = require("mongodb");
//MongoDB connection URL - mongodb://host:port/dbName
var dbHost = "mongodb://localhost:27017/test";
//DB Object
var dbObject;
//get instance of MongoClient to establish connection
var MongoClient = mongodb.MongoClient;
//Connecting to the Mongodb instance.
//Make sure your mongodb daemon mongod is running on port 27017 on localhost
MongoClient.connect(dbHost, function(err, db){
if ( err ) throw err;
dbObject = db;
});
//use the find() API and pass an empty query object to retrieve all records
dbObject.collection("test1").find({}).toArray(function(err, docs){
if ( err ) throw err;
var wordArray = [];
var numArray = [];
for ( index in docs){
var doc = docs[index];
var words = doc['Words'];
var numbers = doc['Numbers'];
wordArray.push({"value": words});
numArray.push({"value" : numbers});
}
}
</script>
Can I do something simple like this and then just access wordArray and numArray?