以HTML显示MongoDB集合数据

编程入门 行业动态 更新时间:2024-10-13 20:14:56

以HTML显示MongoDB集合<a href=https://www.elefans.com/category/jswz/34/1771445.html style=数据"/>

以HTML显示MongoDB集合数据

所以我是MongoDB的新手。

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

这是我所拥有的:

  • 一个Index.js文件(服务器端js)
  • 我有一个名为CustomersDB的MongoDB集合,其中包含一些数据(文档)(我编写了将其保存在此Customers集合中的代码,并且可以正常工作)

我需要:

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

我正在使用的语言和其他语言是:Node.js,Express,EJS,Body Parser,Cors和MongoDB

回答如下:

您将需要连接到集群并获得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/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`);
    }
}

更多推荐

以HTML显示MongoDB集合数据

本文发布于:2024-05-07 00:11:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1753964.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   HTML   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!