是否可以在同一个 Ejs 页面上显示 collections(mongoDb) 和所有 collections 中的每个元素?

Is possible to display collections(mongoDb) and each element from all collections on the same Ejs page?

我正在尝试使用 nodeJs/Express/MongoDb/Ejs(用于 Html 渲染)为我的网站创建一个小论坛 当我试图显示 collections 的内容时,我有一个美妙的消息:“在将它们发送给客户端后无法设置 headers” 我不明白.. 即将创建一个论坛我的网站像所有 collection 一样都是用户发送的问题,每个 collection 都有用户的评论和回复..

这是我的代码,底部是有问题的部分.. 没有那一切工作.. 祝你有个愉快的夜晚

app.get("/vosQuestions",(req,res)=>{    
    let test = db.collection(test1.toString())
    const curseur = db.listCollections().toArray()    
    .then (result=>{ 
        res.setHeader("Content-Type", "text/html")
        res.render("vosQuestions",{collectionName :result })
        res.end()
    })
    .catch(error=>console.error(error))

// Problem part //

    test.find(function(err,results){
        if (err) throw err
        console.log("le find est :"+results)       
        res.render("vosQuestions",{TEST :results })
        res.end()
    })
})

您收到错误:can not set headers after they are sent to the client 因为您在发送响应一次后试图再次将响应发送回客户端。

您需要先获取所有需要的集合或文件,然后才将响应发送回客户端。您只能发回一个回复。

试试这个:

app.get("/vosQuestions",async (req,res)=>{    
    try{

        let test = db.collection(test1.toString())
        let  collectionName = await db.listCollections().toArray()   
        let tests = await test.find();
        res.setHeader("Content-Type", "text/html")
        res.render("vosQuestions",{collectionName: collectionName, TEST :tests })
        res.end()
    }
    catch(error){
        console.error(error)
//send the error response back here.
    }
})

注意:为了更好的可读性,我在这里使用了 async/await。