如何从Firebase cloud functions连接到MongoDb Atlas



我正在尝试按照这个答案从云函数连接到mongodb atlas db。

我使用上面答案中的这段代码:

import { MongoClient } from 'mongodb'
const uri = 'mongodb://<USER>:<PASSWORD>@foo-shard-00-00-xxx.gcp.mongodb.net:27017,foo-shard-00-01-xxx.gcp.mongodb.net:27017,foo-shard-00-02-xxx.gcp.mongodb.net:27017/test?ssl=true&replicaSet=FOO-shard-0&authSource=admin&retryWrites=true'
let client
export default async () => {
if (client && client.isConnected()) {
console.log('DB CLIENT ALREADY CONNECTED')
} else try {
client = await MongoClient.connect(uri, { useNewUrlParser: true })
console.log('DB CLIENT RECONNECTED')
}
catch (e) {
throw e
}
return client
}

然后我有一个这样的函数:

export const myFunction = functions.region('europe-west1').https.onRequest((request, response) => {
console.log(client.isConnected());
});

当我在本地运行firebase serve时,我没有看到"DB 客户端已连接"或"DB 客户端已连接",这意味着没有调用匿名函数。当我尝试访问myFunction中的client变量时,出现错误。

我目前正在学习 Node,所以这可能是一个简单的问题。谢谢

如果你有一些代码要在 Cloud Functions 中运行,你需要调用它。 不可能简单地声明或导出某个函数并期望它运行而不调用它。 如果您希望在代码的全局范围内运行某些内容,请不要将其包装在函数中,或者在全局范围内调用该函数。

最新更新