Jade/Pug渲染对象数组为表格仅显示首个元素的问题排查
问题排查:Pug/Jade仅渲染数组首个对象的原因及修复方案
咱们先拆解下问题根源,再给出针对性的修复方案:
问题出在哪?
首先看你的Node.js查询逻辑:find().toArray()返回的result是包含单个用户对象的数组(因为你按username查询,理论上只会匹配一个用户),所以传递给模板的listaAppunti结构是[ { appunti: [ {...}, {...}, ... ] } ]。
再看你的Pug模板代码:
each appunto, i in listaAppunti tr td a(href='...') #{appunto.appunti[i].titolo}
这里的appunto其实是那个唯一的用户对象,i是外层循环的索引(固定为0),所以你用appunto.appunti[i]只会取到appunti数组的第0个元素——这就是为什么只显示第一条笔记的核心原因!
修复方案(两种可选)
方案1:优化Node.js查询(推荐)
既然你要查询的是单个用户的笔记,直接用findOne()替代find().toArray(),这样能直接拿到用户对象,再把appunti数组单独传给模板,逻辑更清晰:
MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.collection("user").findOne( {username: "mario00"}, { fields: {appunti: 1, "_id": 0} }, function(err, result) { if (err) throw err; console.log(result); // 直接传递appunti数组给模板 res.render('cerca', { listaAppunti: result.appunti }); db.close(); } ); });
对应的Pug模板可以简化为直接遍历笔记数组:
// TABLE APPUNITI .table-responsive table th Titolo th Data th Percorso th Tags // 遍历每个笔记对象 each appunto in listaAppunti tr td a(href='/commenti?id=' + appunto.id) #{appunto.titolo} td= appunto.dataCaricamento td a(href='/files/' + appunto.percorsoFile, download='') #{appunto.percorsoFile} td each tag in appunto.tags a(href='/appunti?tags=' + tag) ##{tag}
方案2:仅修改Pug模板(不改动后端)
如果不想调整后端代码,只需要在Pug里处理嵌套数组的循环:先遍历用户数组(虽然只有一个),再遍历该用户的appunti数组:
// TABLE APPUNITI .table-responsive table th Titolo th Data th Percorso th Tags // 先遍历用户数组(这里只有一个用户) each user in listaAppunti // 再遍历该用户的所有笔记 each appunto in user.appunti tr td a(href='/commenti?id=' + appunto.id) #{appunto.titolo} td= appunto.dataCaricamento td a(href='/files/' + appunto.percorsoFile, download='') #{appunto.percorsoFile} td each tag in appunto.tags a(href='/appunti?tags=' + tag) ##{tag}
验证效果
修复后,你的数据示例里的4条笔记应该都会被渲染出来,包括带有评论和投票的那条Integrali笔记。
内容的提问来源于stack exchange,提问作者Appuntigram
相关产品推荐
相关产品推荐

