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

241
Vistas
How to delete all documents of all collections in Mongoose

Using the Mongoose ODM with a MongoDB instance, how can one delete all documents in all collections of the database instance, without necessarily destroying the collections themselves or their indexes?

For contrast:

await mongoose.connection.db.dropDatabase();

Deletes the given database, including all collections, documents, and indexes.

according to the Mongoose docs, which is not desired.

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

0

Iterate over all collections in the database given by the values of the Connection.prototype.collections hash, and use Query.prototype.deleteMany() to delete every document in the collection.

The deleteMany() query/operation is asynchronous (it returns a Query promise-like object). In order to iteratively perform the operations for all collections, we can map each collection to a promise with an asynchronous callback in which we await the call, and use Promise.all to resolve when all of the queries have resolved.

async function clearCollections() {
  const collections = mongoose.connection.collections;

  await Promise.all(Object.values(collections).map(async (collection) => {
      await collection.deleteMany({}); // an empty mongodb selector object ({}) must be passed as the filter argument
  }));
}
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