我正在尝试遵循this的答案以从云函数连接到mongodb atlas数据库。
我使用上面答案中的代码:
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 CLIENT ALCONNECTY CONNECTED”或“ DB CLIENT RECONNECTED”,这意味着未调用匿名函数。当我尝试访问client
内的myFunction
变量时,出现错误。
我现在正在学习Node,所以这可能是一个简单的问题。谢谢,
答案 0 :(得分:0)
如果要在Cloud Functions中运行某些代码,则需要调用它。不能简单地声明或导出某些函数并期望其运行而不调用它。如果您希望某些内容在代码的全局范围内运行,请不要将其包装在函数中,或者在全局范围内调用该函数。