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

239
Visualizações
Why am I still getting MongoExpiredSessionError even though I'm parsing the json in my azure function?

With regards to my Azure function, I cannot for the life of me figure out why I'm getting MongoExpiredSessionError: Cannot use a session that has ended error when trying to do an extremely simple insertion. I've tried JSON.parse(result); and JSON.stringify(result); but still getting the same error.

I've also tried removing the finally block, tried adding await in front of collection() but still getting the same error. I've pretty much done all the I can that I've found on the web to troubleshoot but to no avail.

What am I doing wrong?

Here's my code:

const mongo = require('mongodb');
const MongoClient = require('mongodb').MongoClient;
const uri = "myUri"

module.exports = async function (context, req) {
    const client = await MongoClient.connect(uri, {useNewUrlParser:true}).catch(err => {context.log(err); });

    let result = null;
    let callerEntityProfile = req.body.CallerEntityProfile;
    let packIdInput = callerEntityProfile.Entity.PackIdInput;
    let userId = callerEntityProfile.Entity.UserID;

    try {
        const db = await client.db("myDB");
        let collection = await db.collection("myCollection");
        let query = { userId : userId };
        result = await collection.findOne(query);

        let insertPack = {
          "PackId" : packIdInput
        };

        result.packsOwned.push(insertPack);

        JSON.parse(result);

        collection.insertOne(result, function(err, r) {
          console.log('inside insertOne')
          console.log(err); // this is where it's showing the error message
        });

    }
    catch (err) {
        context.log(err);
    }
    finally {
        client.close();
    }

   
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since it does not wait until the end of the asynchronous function, the close action is faster than insertMany action. You can try the following:

const DB = client.db(databasename);

const myAsyncFunction = async() => {
  const collection = await DB.collection(nameofcollection); // do this INSIDE async function

  await collection.insertMany(details); // similarly inside async
};

client.close();

Alternatively, you may try something like this:

client.connect(err => {
  if(err) return console.log(err);

  client.db(databasename).collection(nameofcollection)
      .then(collection => collection.insertMany(details))
      .then(() => client.close());
});

You can refer to these similar SO threads -
How to fix MongoError: Cannot use a session that has ended
MongoError: Cannot use a session that has ended
Node js throws MongoError
MongoError

about 4 years ago · Juan Pablo Isaza 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