user8264407
user8264407

Reputation:

Display MongoDB Collection Data in HTML

So I'm new to MongoDB.

I am developing a website that I would like to GET data from a MongoDB collection based on a {Name: String} within that Collection and display it in an HTML Table.

This is what i have:

What i need:

What kind of code do I write in my index.js file for app.get('/customers') that would allow me to GET the data from the collection and display it in a table in my customers.ejs file.

The languages and others that I am using for this is: Node.js, Express , EJS, Body Parser, Cors and MongoDB

Upvotes: 0

Views: 5903

Answers (1)

Lauren Schaefer
Lauren Schaefer

Reputation: 706

You'll need to connect to your cluster and get a MongoClient just as you did to insert the data. Then you can use find({}) to search for all documents in the collection. Below is some sample code to get you started.

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`);
    }
}

This code is based on code from my Node.js Quick Start series: https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-read-documents.

Upvotes: 3

Related Questions