Node.js 为数组的每个元素生成
我试图为数组中的每个元素生成一个,以便在列表中显示它,我尝试了许多方法,例如join、forEach和其他方法,但没有成功Node.js 为数组的每个元素生成,node.js,Node.js,我试图为数组中的每个元素生成一个,以便在列表中显示它,我尝试了许多方法,例如join、forEach和其他方法,但没有成功 app.get("/", (req, res) => { db.db() .collection("notes") .find() .toArray(function(e, d) { let items = d items.forEach(item => {console.log(item)})
app.get("/", (req, res) => {
db.db()
.collection("notes")
.find()
.toArray(function(e, d) {
let items = d
items.forEach(item => {console.log(item)})
res.end(`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Server</title>
</head>
<body>
<h1> Server running! </h1>
<ul>
<p>${JSON.stringify(items.join('</br>'))}</p>
</ul>
</body>
</html>`);
db.close();
});
})
我希望每个阵列组件都是这样的:
{id:5c3f7c25ae62eb0741735d6b,文本:'2019-01-16 19:47:01',标题:'IOT设备直播!'
将显示在列表中的页面中,这就是我尝试添加右键的原因,如果我使用join函数,它不会工作,但数组元素显示为对象,我无法读取文本。join方法将返回字符串,因此它将在其所有元素上调用toString。因为这里的元素是对象,所以对它们调用toString将把它们转换成字符串[object]。您应该首先使用JSON.stringify映射数组,然后加入结果:
items = items.map(JSON.stringify);
let output = items.join('<br />');
我一直在找这个!我知道打电话给toString有问题。谢谢!