我正在尝试学习如何获取已存储在MongoDB中的数据并将其显示为HTML格式的表格。我从未使用过HTML或JavaScript,所以我决定首先在HTML代码中创建一个脚本并使用循环显示一个简单的表:
<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>
我得到的输出是:
One 1
Two 2
Three 3
Four 4
Five 5
Six 6
Seven 7
现在我想出了语法是如何工作的,我想使用像NodeJS / ExpressJS / Mongoose这样的东西从MongoDB获取文档并将它们存储到一个数组中并将它们显示为一个表。
db test
和集合test1
中已存在的MongoDB架构是:
{
"_id": ObjectId("fffffffffffffff"),
"Words": "One",
"Numbers": 1
}
{
"_id": ObjectId("aaaaaaaaaaaaaaa"),
"Words": "Two",
"Numbers": 2
}
...
我想查询并存储&#34; Words&#34;的值。和&#34;数字&#34;从文档到数组wordArray
和numArray
,并将它们显示为表格。
我发现了这些相关的问题:
Displaying MongoDB Documents with HTML
Display MongoDB values in HTML
How to use HTML in Express framework with nunjucks- no jade
我将如何做我想做的事?我应该看一下这些链接中的哪一个?因为我迷失了,不知道从哪里开始。是否有捷径可寻?我尝试了以下操作:
<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>
我可以做这样简单的事情,然后只需访问wordArray和numArray吗?
答案 0 :(得分:1)
好的,这个例子基于MongoDB驱动程序,你使用包装如猫鼬或僧侣是可取的。首先从数据库中提取数据并将其存储在数组中。例如,在存储arr = ['dta','nio']
之后将这些数据指向您的视图或网页,您需要一个模板绑定引擎,我通常使用EJS,因为它简单而自然.EJS结合数据和模板来生成HTML。因此,您将JavaScript变量绑定到html文件。这是ejs。http://www.embeddedjs.com/
要与mongoose一起说明,这是一个很棒的链接。https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications
以下是EJS与节点https://scotch.io/tutorials/use-ejs-to-template-your-node-application
的链接