Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
Getting "MongoExpiredSessionError: Cannot use a session that has ended" when using forEach to update document but why?

I'm just trying to upsert a key value pair i.e. {mark : done} to my Mongo database using id that I have stored in an array.

But for the life of me I can't figure out why if I use a for loop it works fine. But if I use a forEach loop, it gives me a "Cannot use a session that has ended" Error.

I'm hoping someone SO assist in explaining why this happens

Boiler Plate Code

import { MongoClient } from "mongodb";
const uri = "mongodb://localhost:27018/";
const client = new MongoClient(uri);

Function with "for loop" implementation

async function updateMongo1() {
    const db = client.db("testDB");
    const coll = db.collection("testCollection");
    await client.connect();
    try {
        let array = [
            "2021-10-18",
            "2021-10-17",
            "2021-10-16",
            "2021-10-15",
            "2021-10-14",
        ];
        for (let i = 0; i < array.length; i++) {
            await coll.updateOne(
                { _id: array[i] },
                { $set: { mark: "done" } },
                { upsert: true }
            );
        }
    } catch (e) {
        console.error(e.message);
    } finally {
        await client.close();
    }
}

Function with "forEach" implementation

async function updateMongo2() {
    const db = client.db("testDB");
    const coll = db.collection("testCollection");
    await client.connect();
    try {
        let array = [
            "2021-10-18",
            "2021-10-17",
            "2021-10-16",
            "2021-10-15",
            "2021-10-14",
        ];

        array.forEach(async (element) => {
            await coll.updateOne(
                { _id: element },
                { $set: { mark: "done" } },
                { upsert: true }
            );
        });
    } catch (e) {
        console.error(e.message);
    } finally {
        await client.close();
    }
}

running different implementations yields different results.

(async () => {
    //await updateMongo1(); //-> this works
    await updateMongo2(); //-> this gives "MongoExpiredSessionError: Cannot use a session that has ended" what gives??
})();

Please let me know why this happens?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The element variable is an array e.g. ["2021-10-18"]. In the second implementation, you were meant to access element[0] but forgot to so you put an array into the _id field.

I don't know if that's what's specifically causing your error but it is an error in the implementation.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda