Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
How to properly connect to MongoDB using Cloud functions?

I would like to connect to my Atlas cluster only once per instance running Cloud Functions.

Here is my code for an instance :

const MongoClient = require("mongodb").MongoClient;

const client = new MongoClient("myUrl", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

exports.myHttpMethod = functions.region("europe-west1").runWith({
  memory: "128MB",
  timeoutSeconds: 20,
}).https.onCall((data, context) => {
  console.log("Data is: ", data);
  client.connect(() => {
    const testCollection = client.db("myDB").collection("test");
    testCollection.insertOne(data);
  });
});

And i would like to avoid the client.connect() in each function call that seems to be really too much.

I would like to do something like this :

const MongoClient = require("mongodb").MongoClient;

const client = await MongoClient.connect("myUrl", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = client.db("myDB");

exports.myHttpMethod = functions.region("europe-west1").runWith({
  memory: "128MB",
  timeoutSeconds: 20,
}).https.onCall((data, context) => {
  console.log("Data is: ", data);
  const testCollection = db.collection("test");
  testCollection.insertOne(data);
});

But i can't await like this.
In my AWS Lambda functions (running in python) i have not this issue and i am able to connect only once per instance, so i guess there is an equivalent but i don't know much JS / Node JS.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can store your database client as a global variable. From the documentation,

Cloud Functions often recycles the execution environment of a previous invocation. If you declare a variable in global scope, its value can be reused in subsequent invocations without having to be recomputed.

Try refactoring the code as shown below:

import * as functions from "firebase-functions";

import { MongoClient } from "mongodb"; 

let client: MongoClient | null;

const getClient = async () => {
  if (!client) {
    const mClient = new MongoClient("[MONGODB_URI]", {});
    client = await mClient.connect();
    functions.logger.log("Connected to MongoDB");
  } else {
    functions.logger.log("Using existing MongoDB connection");
  }
  functions.logger.log("Returning client");
  return client;
};

export const helloWorld = functions.https.onRequest(
  async (request, response) => {
    const db = (await getClient()).db("[DATABASE]");
    const result = await db.collection("[COLLECTION]").findOne({});
    response.send("Hello from Firebase!");
  }
);

This should reuse the connection for that instance.

enter image description here

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda