javascript - 当客户端不在范围内时如何在 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}');
}
})
解决方案
推荐阅读
- ios - 在 RxSwift 中嵌套订阅调用
- git - 如何使用起源中的新分支更新 gitlab 分叉
- php - artisan config:cache 和其他优化是否会影响我的数据库(Laravel)
- powershell - 解析来自 Invoke-PsExec 的 PowerShell 响应
- c# - 无法获取 TaskCompletionSource 的结果
- amazon-web-services - 如何在我们的本地 Ubuntu 服务器上复制 AWS AMI?
- ruby-on-rails - 未经授权的用户可以创建任务,如何取消此功能?
- php - Laravel 5.2 队列 - 延迟不起作用
- java - 仅在下载 PDF 格式时将日期从 MM/dd/yyyy 转换为 MMddyyyy
- javascript - 如何检查不是对象数组的响应长度