0

I want to pass data to my mongo database but the createOrderHistoryListing function requires the client variable and that is only within the scope of the dbConnect function. How can I restructure my code or a more efficient way to have access to client variable and make database calls in separate GET/POST functions?

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

async function dbConnect() {

    const uri = "mongodb+srv://foo:bar@cluster-foo-bar.mongodb.net/test?retryWrites=true&w=majority";

    const client = new MongoClient(uri);

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

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

dbConnect().catch(console.error);

app.post('/webOrderForm', function (req, res) {
    let accNum = req.body.accNum

    // Store order history document in mongoDB
    async function createOrderHistoryListing(client, newListing){

        const result = await client.db("order_history").collection("orderHistory").insertOne({accNum: accNum});
        console.log('New listing created with the following id: ${result.insertedId}');
    }
})
Jakkie Chan
  • 317
  • 4
  • 14
  • Look into the singleton pattern to connect to the database – Ayush Gupta Mar 30 '20 at 19:04
  • Does this answer your question? [How to properly reuse connection to Mongodb across NodeJs application and modules](https://stackoverflow.com/questions/24621940/how-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module) – SuleymanSah Mar 30 '20 at 19:26

0 Answers0