如何在HTML中显示mongoDB集合? [英] How to display mongoDB collection in html?

查看:320
本文介绍了如何在HTML中显示mongoDB集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是猫鼬的初学者,想在基本html列表中的"example.ejs"文件中显示"exColl"集合中的mongoDB文档.关于该主题还有其他文章,但我对此仍然感到困惑.

I am a beginner with mongoose and would like to display a mongoDB document(s) from "exColl" collection in a file called "example.ejs" in a basic html list however I have hit various problems. There are other posts on this topic yet I remain stumped by this.

-我确实有一段工作代码,可以使用res.json从exColl.find({})输出所有文档,显然是将它们置于json格式.但是,我无法将这段代码改编成可以使用res.render进行工作的代码.

-I do have a working chunk of code that outputs all documents from exColl.find({}) using res.json, obviously putting them in json format. However I have been unable to adapt this code into something that works using res.render for example.

-当我在app.js中定义一个变量并尝试在example.ejs中访问它时,找不到该变量,因此即使我可以将exColl.find({})的结果保存在一个变量中,我也不会看不到如何将其输入到HTML

-When I define a variable in app.js and try to access it in example.ejs the variable is not found, therefore even if I could save the results of exColl.find({}) in a variable I don't see how I would be able to enter it into the HTML

很明显,我不知道我所不知道的是什么非常令人沮丧.如果有人可以帮助填补我在概念上的空白,那将是极好的.

Clearly I don't know what I don't know which is very frustrating. If someone could help fill my conceptual gaps that would be fantastic.

-编辑- 添加我尝试过的代码段

---Edit---- Adding a snippet I have tried

app.get("/example", function (req, res){
    exColl.find({})
    .exec(function (err, examples){
        if (err) {
            res.send("an error has occurred")
        } else res.render(examples: examples);
        });
    });

在.ejs文件中

<p> <%= examples %> </p>

推荐答案

您的问题似乎是EJS语法,您应该在此处进行检查:

Your problem seems to be the EJS syntax which you should review here: EJS Docs. Consider the following test project structure:

.
├── index.js
├── package.json
├── setup.js
└── views
    ├── index.ejs
    └── table.ejs

我用 setup.js 创建一个测试数据库,以便我们显示一些虚拟帖子:

I create a test DB with setup.js so that we have some dummy posts to display:

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:8081/test", {
    useNewUrlParser: true
});

const Post = mongoose.model("Post", {
    title:String,
    body: String
});

const toMake = [
    {title: "hello", body: "world"},
    {title: "foo", body: "bar"},
    {title: "fizz", body: "buzz"},
    {title: "a", body: "b"}
];

Post.insertMany(toMake)
    .then(()=>{
        console.log("done");
        mongoose.connection.close();
    })
    .catch(err => console.error(err));

我创建了一个EJS模板 views/table.ejs 以将我的帖子呈现为表格:

I create an EJS template views/table.ejs to render my posts as a table:

<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Body</th>
        </tr>
    </thead>
    <tbody>
        <% posts.forEach(post => { %>
            <tr>
                <td><%= post.title %></td>
                <td><%= post.body %></td>
            </tr>
        <% }) %>
    </tbody>
</table>

然后我创建一个EJS模板 views/index.ejs 以使用表格模板

I then create an EJS template views/index.ejs to use the table template

<main>
    <h1>Posts</h1>
    <%- include("table", {posts}); %>
</main>

我还使服务器响应 index.js 中的请求,并使用node index.js运行它:

I also make a server to respond to requests in index.js and run it with node index.js:

const express = require("express");
const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:8081/test", {
    useNewUrlParser: true
});

const app = express();

const Post = mongoose.model("Post", {
    title: String,
    body: String
});

app.set("view engine", "ejs");

app.get("/", async (req, res) => {
    const posts = await Post.find({});
    res.render("index", {posts});
});

app.listen(3000, () => console.log("Listening"));

当我curl localhost:3000时,我获得了呈现的HTML:

And when I curl localhost:3000 I get the rendered HTML:

<main>
    <h1>Posts</h1>
    <table>
        <thead>
            <tr>
                <th>Title</th>
                <th>Body</th>
            </tr>
        </thead>
        <tbody>

                <tr>
                    <td>hello</td>
                    <td>world</td>
                </tr>

                <tr>
                    <td>foo</td>
                    <td>bar</td>
                </tr>

                <tr>
                    <td>fizz</td>
                    <td>buzz</td>
                </tr>

                <tr>
                    <td>a</td>
                    <td>b</td>
                </tr>

        </tbody>
    </table>
</main>


无论如何,我都需要将数据馈送到res.render()函数,并使用呈现所需的所有数据填充呈现范围.


No matter what, I will need to feed data to the res.render() function and populate the render scope with all the data needed to render.

但是,我已经使 table.ejs 可重用.因此,可以说我还有一个页面,希望能够以表格形式显示其中的一些帖子.

However, I have made table.ejs reusable. So lets say that I have another page that I want to be able to show some of the posts in a tabular fashion.

我还有另一个EJS模板: views/profile.ejs ,如下所示:

I have another EJS template: views/profile.ejs that looks like this:

<main>
    <h1>2 Posts</h1>
    <%- include("table", {posts: posts.slice(0, 2)}); %>
</main>

然后在/sliced处向我的应用程序添加另一条路由:

And I add another route to my application at /sliced:

app.get("/sliced", async (req, res) => {
    const posts = await Post.find({});
    res.render("profile", {posts});
});

每当我卷曲localhost:3000/sliced时,我只会得到帖子中的前2个项目,因为我只用所有帖子的一部分填充了include的作用域:

Whenever I curl localhost:3000/sliced I get only the first 2 items in the posts since I only populated the include's scope with a slice of all the posts:

<main>
    <h1>2 Posts</h1>
    <table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Body</th>
        </tr>
    </thead>
    <tbody>

            <tr>
                <td>hello</td>
                <td>world</td>
            </tr>

            <tr>
                <td>foo</td>
                <td>bar</td>
            </tr>

    </tbody>
</table>

</main>

这篇关于如何在HTML中显示mongoDB集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆