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

196
Vistas
How do I get mongoose to await the creation of documents before disconnecting

I can't seem to find an answer anywhere as to what I'm doing wrong here. I just want to wait for my for-loop to finish seeding my database before disconnecting

database.js

import mongoose from 'mongoose';

mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost/db', { useNewUrlParser: true, useUnifiedTopology: true });

const exampleSchema = new mongoose.Schema({
    name: String,
    img: String,
});

const Example = mongoose.model('Example', exampleSchema);

export default Example;

seed.js

import axios from 'axios';
import mongoose from 'mongoose';
import Example from './database.js';

const seedExample = async () => {
    const { data } = await axios.get(api placeholder);

  for (let i = 0; i < data.length; i++) {
    await Example.create({
      name: data[i].name,
      img: data[i].img,
    }, (err, example) => {
      if (err) return err
    })
  }
};

await seedExample();
mongoose.disconnect()

If I set a timeout then disconnect the documents are created but otherwise, it just closes before the function even completes. I've tried putting the disconnect at the end of the for loop as well.

Go easy on me I'm a noob, any advice all around very welcome. Thanks!

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can have the seedExample function as a Promise and you can call the mongoose.disconnect() function in the then() block

Your code would then look like this:

const seedExample = new Promise(function(resolve, reject){
    const { data } = await axios.get(api placeholder);
    
    for (let i = 0; i < data.length; i++) {
        await Example.create({
          name: data[i].name,
          img: data[i].img,
        }, (err, example) => {
          if (err) reject(err) 
        })
    }
    resolve('created')
})

seedExample.then((res)=>{
    console.log(res)
    mongoose.disconnect()
})
.catch((err)=>{
    console.log(err)
})
about 4 years ago · Santiago Trujillo 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