【问题标题】:How to number a table consecutively by the amount of Objects that are in a mongoDB?如何按 mongoDB 中的对象数量连续对表进行编号?
【发布时间】:2019-12-25 08:11:33
【问题描述】:

我有一个表,想按我在 mongoDB 中的记录数量对其进行编号。除了编号之外,一切正常...

我尝试了循环和 .length,但它破坏了我的应用程序。

我的架构:

var userInputSchema = new mongoose.Schema({
    name: String,    
    address: String,
    phone: Number
});

<table class="table">
    <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">NAME</th>
            <th scope="col">ADDRESS</th>
            <th scope="col">PHONE</th>
        </tr>
    </thead>

    <tbody>
        <% userInputs.forEach(function(userInput) { %>
        <tr>
 //this won't work <th scope="row"><% userInput[].length %></th>
            <td><%=userInput.name %></td>
            <td><%=userInput.address %></td>
            <td><%=userInput.phone %></td>

        </tr>
        <% }); %>
    </tbody>
</table>

应该是这样的:

#  NAME     ADDRESS       PHONE
1  Gary     Evergrenn     123213
2  Tom      Street        2333434
3  Fox      Jonahill      3434355

“#”列应该根据这个 mongoDB 中的记录数量自动编号,但我不能让它工作。 它是空的,否则会因“内部服务器错误”而破坏整个页面。

【问题讨论】:

    标签: javascript node.js mongodb ejs


    【解决方案1】:

    尝试利用forEach方法的索引参数。

    <table class="table">
    <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">NAME</th>
            <th scope="col">ADDRESS</th>
            <th scope="col">PHONE</th>
        </tr>
    </thead>
    
    <tbody>
        <% userInputs.forEach(function(userInput, index) { %>
        <tr>
            <th scope="row"><%=++index %></th>
            <td><%=userInput.name %></td>
            <td><%=userInput.address %></td>
            <td><%=userInput.phone %></td>
        </tr>
        <% }); %>
    </tbody>
    

    您需要在打印之前增加索引。

    【讨论】:

    • 赞成,我删除了我的答案,我忘记了“在打印之前增加索引”部分:P
    • 是的,我在发布我的答案后看到了你的答案。我的回答和你的差不多。
    • 完美,感谢您的工作,也感谢 Margon 的帮助!我还是个初学者...(另外我忘记了“=”任何遇到同样问题的人)
    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多