首页 > 解决方案 > 以 HTML 格式显示 MongoDB 集合数据

问题描述

所以我是 MongoDB 的新手。

我正在开发一个网站,我想根据该集合中的 {Name: String} 从 MongoDB 集合中获取数据,并将其显示在 HTML 表中。

这就是我所拥有的:

我需要的:

我在我的 index.js 文件中为 app.get('/customers') 编写了什么样的代码,这将允许我从集合中获取数据并将其显示在我的 customers.ejs 文件的表中。

我为此使用的语言和其他语言是:Node.js、Express、EJS、Body Parser、Cors 和 MongoDB

标签: node.jsmongodbexpressejs

解决方案


您需要连接到您的集群并获得一个 MongoClient,就像您插入数据一样。然后您可以使用 find({}) 搜索集合中的所有文档。下面是一些示例代码,可帮助您入门。

const { MongoClient } = require('mongodb');

async function main() {
    /**
     * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
     * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
     */
    const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";

    /**
     * The Mongo Client you will use to interact with your database
     * See https://mongodb.github.io/node-mongodb-native/3.3/api/MongoClient.html for more details
     */
    const client = new MongoClient(uri);

    try {
        // Connect to the MongoDB cluster
        await client.connect();

        await findCustomers(client);

    } finally {
        // Close the connection to the MongoDB cluster
        await client.close();
    }
}

main().catch(console.error);


async function findCustomers(client) {

    // See https://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#find for the find() docs
    const cursor = client.db("NameOfYourDB").collection("NameOfYourCollection").find({});

    // Store the results in an array. If you will have many customers, you may want to iterate
    // this cursor instead of sending the results to an array. You can use Cursor's forEach() 
    // to do the iterating: https://mongodb.github.io/node-mongodb-native/3.3/api/Cursor.html#forEach
    const results = await cursor.toArray();

    // Process the results
    if (results.length > 0) {
        results.forEach((result, i) => {

            console.log(result);
            // Here you could build your html or put the results in some other data structure you want to work with
        });
    } else {
        console.log(`No customers found`);
    }
}

此代码基于我的 Node.js 快速入门系列中的代码:https: //www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-read-documents


推荐阅读