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

189
Visualizações
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 Respostas
Responde à pergunta

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 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