【问题标题】:How do I tailor my query to get a specific title?如何定制我的查询以获得特定的标题?
【发布时间】:2021-08-10 16:42:00
【问题描述】:

我的app.js 文件中有一个查询,该查询呈现到我的列表页面list.ejs 中找到http://localhost:4100/list。顾名思义,list 页面显示了存储在数据库中的ALL交易列表,但我更感兴趣的是只显示严格在内罗毕

在下面找到我的app.js 文件的内容:

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

let countyName;
countyName = transModel.findOne({ transCounty : /Nairobi/i, })
                                    .limit(5)
                                    .select({ transCounty:1})
                                    .exec( (err, result)=> {
                                        
                                    if (err) throw err;
                                           console.log('>> ' +result); 
                                           return result;
                                        });
                                        
console.log ('countyName: ' +countyName);

transModel.find( (err, docs)=> {
if (!err) 
    {
        res.render('list',  {data : docs, countyName: countyName}); 
    }
else
    {
//          res.status(status).send(body);      
    }
        
 })

});

在终端中,上面的代码输出:

countyName: undefined
>> { _id: 609f7ed8fe1fd8b3193b0b77, transCounty: 'Nairobi' }

我的list.ejs 看起来像这样:

<h1> Transactions </h1>

<p>
 Name of County: <%= countyName %>  
</p>

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

上述list.ejs 文件虽然正确地呈现了包含数据库中所需内容的表,但无法选择 的名称。请帮助我弄清楚如何实现这一目标。

在下面找到渲染的list.ejs 的图像:

请注意县名未定义。 如何制定我的查询,以便仅产生内罗毕内的所有交易,并在 ejs 文件中显示县名。

期待您的帮助。

【问题讨论】:

  • 您无需等待承诺解决。你用什么 ORM?
  • @Michael 谢谢,我如何等待承诺解决?你能给我一个代码示例吗?
  • 你用什么orm?
  • @Michael 抱歉,我使用 Mongoose ORM

标签: node.js mongoose mongodb-query


【解决方案1】:

在使用它的值之前,你应该等待承诺解决:

countyName = await transModel.findOne({
        transCounty: /Nairobi/i,
    })
    .limit(5)
    .select({
        transCounty: 1
    })
    .exec();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
相关资源
最近更新 更多