You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB文档渲染问题求助:无法展示active状态的Draft数据

问题:Pug模板无法渲染MongoDB文档字段

问题原因

  1. 投影设置限制了返回字段
    你的查询中使用了projection: { homeSchedule: 1 },这会让MongoDB只返回homeSchedule和默认的_id字段,其他需要渲染的字段(如draftState、draftCreate等)都不会被包含在查询结果里。

  2. 未将MongoDB游标转为可遍历数组
    collection.find()返回的是游标对象,而非直接可遍历的数组,Pug的each语法无法直接遍历游标,必须先将其转换为数组。

修复后的代码

controller/home.js

const homeView = (req, res, next) => {
    const client = new MongoClient(uri);

    async function run() {
        try {
            const database = client.db("ticketdrafterDB");
            const collection = database.collection("drafts");

            const query = { draftState: "active" };
            // 移除投影参数,或者明确列出需要返回的所有字段
            // 如果只需要特定字段,改为:projection: { draftState: 1, draftCreate: 1, homeTeam: 1, draftOwner: 1, homeSchedule: 1 }
            const draftsCursor = collection.find(query);

            // 将游标转为数组
            const drafts = await draftsCursor.toArray();

            if (drafts.length === 0) {
                console.log("No documents found!")
            }
            
            res.render('index', { drafts: drafts });
        } finally {
            await client.close();
        }
    }
    run().catch(console.dir);
};

index.pug(可保留或按需扩展)

each draft in drafts
    li.list-group-item
        p 状态:#{draft.draftState}
        p 创建时间:#{new Date(draft.draftCreate).toLocaleString()}
        p 主队:#{draft.homeTeam}
        p 创建者:#{draft.draftOwner}

额外说明

  • 如果不需要返回所有字段,建议在projection中明确列出需要的字段,避免返回冗余数据,示例:
    const options = { 
        projection: { 
            draftState: 1, 
            draftCreate: 1, 
            homeTeam: 1, 
            draftOwner: 1,
            homeSchedule: 1 
        } 
    };
    const draftsCursor = collection.find(query, options);
    
  • draftCreate是时间戳,在Pug中可以用new Date()转换为可读的日期格式。

内容的提问来源于stack exchange,提问作者h8t4nk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:06:22