首页 > 解决方案 > 当客户端不在范围内时如何在 NodeJS 中更新 mongoDB

问题描述

我想将数据传递给我的 mongo 数据库,但该createOrderHistoryListing函数需要客户端变量,并且仅在dbConnect函数的范围内。如何重构我的代码或更有效的方式来访问client变量并在单独的 GET/POST 函数中进行数据库调用?

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

标签: javascriptnode.jsmongodbexpressmongodb-query

解决方案


推荐阅读