【问题标题】:How do I rendering views based on multiple queries in Express?如何在 Express 中基于多个查询呈现视图?
【发布时间】:2021-08-11 12:18:14
【问题描述】:

我有一个包含各种data 的集合,我希望喜欢在呈现我的ejs 页面时使用这些集合。我似乎只能从 ONE 查询而不是其他查询中呈现内容。

请帮我弄清楚如何从其他查询中呈现内容。

在下面找到我收藏的一些内容:

在我呈现的ejs 页面下方查找

特别注意Transactions from: Unidentified句中的Unidentified

现在...让我们看看生成此页面的代码:

function county (req, res) {
transModel.findOne({ transCounty : /Nairobi/i,
                        })
                        .limit(5)
                        .select({ transCounty:1})
                        .exec( (err, result)=> {
                            if (err) throw err;
                                console.log('>> ' +result); 
                                console.log('We in county function!');
                                return result;
                            });    
};

app.get('/list', async (req,res)=> {

console.log('## ' +county());
transModel.find({transIndustry: 'Pharmacy'}, (err, docs)=> {
if (!err) 
    {
        res.render('list',  {data : docs, countyName: county}); 
    }
else
    {
//          res.status(status).send(body);      
    }
        
})
});

在控制台中,上面的代码记录:

## undefined
>> { _id: 609f7ed8fe1fd8b3193b0b77, transCounty: 'Nairobi' }
We in county function!

现在在ejs文件内容下方找到:

<body>
    <h1> 
        Transactions
    </h1>

    <p> Transactions from: <b> <%= countyName.transCounty %> </b> County: </p>

    <table>
        <tr>
            <th> _id  </th>
            <th> Transaction Amount </th>       
            <th> Transaction Industry </th> 
        </tr>
        <% data.forEach(function(entry) {%>
        <tr>
            <td> <%=entry._id%> </td> 
            <td> <%=entry.transAmount%> </td>               
            <td> <%=entry.transIndustry%> </td>     
        </tr>
        <%});%>
        
    </table>

请帮助我了解我哪里出错了,以及如何让&lt;%= countyName.transCounty %&gt; 在我渲染的ejs 文件中显示Nairobi

【问题讨论】:

    标签: node.js mongodb express mongoose ejs


    【解决方案1】:

    docscounty 之间的主要区别在于docs 是数据库查询的结果(好的!),而county 是一个您仅引用且从不运行的函数 (问题 1),但如果你要运行它,它仍然不会返回任何内容(问题 2),但它确实会运行一个查询,所以你可以做到!

    所以,这不是完整的解决方案,只是为您指明正确的方向:

    • 您需要在某个时候使用带括号的county() 调用县。
    • 由于数据库查询的性质是异步的,您需要使用回调模式基于承诺的解决方案

    回调解决方案可能如下所示:

       // Here we are calling the function, and the entire function-argument is the callback.
       county((countyResult /* the callback will be called with result in the future */) => {
            // wrap your existing code, 
            // because the result will only be available inside the callback
            transModel.find({transIndustry: 'Pharmacy'}, (err, docs) => {
                ...
                res.render('list', {data : docs, countyName: countyResult});
            });
       });
    

    被调用的函数可能看起来像这样:

    function county (callback /* accept a callback */) {
        transModel.findOne({ transCounty : /Nairobi/i })
            .limit(5)
            .select({ transCounty:1})
            .exec((err, result) => {
                if (err) throw err;
                callback(result);  // Use the callback when you have the result.
            });    
    }
    

    因为需要包装回调,所以结果永远不会变得非常漂亮。

    相反你可以使用承诺。例如:

    let countyResult = await county();
    let docs = await transModel.find({transIndustry: 'Pharmacy'}).exec();
    res.render('list', {data : docs, countyName: countyResult});
    

    被调用的函数可能看起来像这样:

    function county (req, res) {
        return transModel
            .findOne({ transCounty : /Nairobi/i })
            .limit(5)
            .select({ transCounty: 1})
            .exec();  // If you use exec without a callback it'll return a promise.
    };
    

    这样更简洁,但需要使用 try/catch 进行错误处理。 例如:

    let countyResult;
    try {
         countyResult = await county();
    catch(err) {
        throw err; 
        // Of course, if all you do is throw, then you don't even need the `try/catch`.
        // Try/catch is to catch thrown errors and handle them.
    } 
    

    您可能仍想检查结果是否包含任何内容。没有找到数据的查询不是错误。

    免责声明:代码用于描述流程。我试着把它弄对了,但这里没有任何测试,所以肯定会有错误。

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      相关资源
      最近更新 更多