Node.js 如何读取mongodb并在nodejs中输出?

Node.js 如何读取mongodb并在nodejs中输出?,node.js,Node.js,如何在不使用express/view引擎的情况下将行(文档)输出为html表格格式。我试图编写res.write(${documents}),但它不起作用。请检查以下代码 const http = require('http'); const MongoClient = require('mongodb').MongoClient; const hostname = '127.0.0.1'; const port = 3000; const url = 'mongodb://localhost

如何在不使用express/view引擎的情况下将行(文档)输出为html表格格式。我试图编写res.write(
${documents}
),但它不起作用。请检查以下代码

const http = require('http');
const MongoClient = require('mongodb').MongoClient;

const hostname = '127.0.0.1';
const port = 3000;
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useNewUrlParser: true });
var documents;
client.connect(err => {
  const collection = client.db("mydb").collection("messages");
  collection.find({}).toArray(function(err, docs) {
    console.log("Found the following records");
    console.log(docs); // How can write this docs as html table
    documents = docs; // Is there any workaround for this?
  });
  client.close();
});

const server = http.createServer((req,res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.write(`Server running at http://${hostname}:${port}/. Records:${documents}`); //this document not appearing
  res.end();
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
请就

//如何将此文档编写为html表格


您是否尝试过console.table()而不是console.log()?

代码的一个问题是标题

res.setHeader('Content-Type', 'text/plain');
您需要设置内容类型
text/html

如果要将JSON映射到HTML,请尝试以下操作

let myObj
txt += "<table border='1'>"
for (x in myObj) { txt += "<tr><td>" + myObj[x].name + "</td></tr>"; } 
txt += "</table>" 
document = txt;
let myObj
txt+=“”
对于(myObj中的x){txt+=“”+myObj[x].name+“”;}
txt+=“”
document=txt;

您需要从JSON生成HTML标记或将JSON映射到HTML,对吗?如果是这样,请尝试此操作,让myObj txt+=“”for(myObj中的x){txt+=“”+myObj[x]。name+“”;}txt+=“”document=txt;我知道问题的范围是否不同,谢谢你的回答。console.table()输出得很好。我想在浏览器标记中输出这样的表。嗨,阿赞,谢谢你的及时回复。我已经复制粘贴了你的代码。但输出显示“未定义”。您能正确格式化代码并建议我如何在res.write()中输出吗?谢谢。嗨,艾森,我更正了格式。现在它终于起作用了。谢谢