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

155
Visualizações
Can not model.find the documents I have just saved into my mongoose

this is what im going trough right now: I am inserting some values into a collections called fruits and right after its done i want to console.log each of them with map, the first try the console outputs instead of a fruit(a single collection object) all the fruits(model or collection) object, but when i run again the same code(so that i adds again the same values to the collection fruits) the console display the fruits objects that have been inserted before followed by again more fruit(model or collection) object. what can i do so that i can make use of the documents i have just inserted in to my collection? THis is the code:

const db = require("mongoose");
const url = "mongodb://localhost:27017/personasDB";
db.connect(url);

const fruitSchema = new db.Schema({
    name:{
        type: String,
        required: true,
        minlength: 3,
        maxlength: 20
    },
    price:{
        type: Number,
        required:true,
        min: 0,
        max: 100
    }
});
const Fruit = db.model("fruits", fruitSchema);

const fruits = ["pineapple", "apple", "banana", "orange"];
const prices = [12, 12.5, 4, 6.4];

for(let i = 0; i < fruits.length; i++){
    const fruit = new Fruit({
        name: fruits[i],
        price: prices[i]
    });
    fruit.save();
    
}
console.log(Fruit.find({}, function(err, elements){
    if(err){
        console.log(err);
    }else{
        elements.map(fruit=>{
            console.log(fruit);
        });
    }
}));

the first log

after i rerun the code i get what i want right after the firt outputs

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

0

The problem is that the save() method is asynchronous. You can't update your database on one line and assume it's already changed on the next one. You'll likely log the unchanged documents.

You could try to use Array#map() to get an array of promises and wait for all the documents to be saved in parallel using Promise.all(). Once all the docs are saved you can go and use Fruit.find().

const fruits = ['pineapple', 'apple', 'banana', 'orange']
const prices = [12, 12.5, 4, 6.4]

let promises = fruits.map((fruitName, i) => {
  const fruit = new Fruit({
    name: fruitName,
    price: prices[i],
  })
  return fruit.save()
})

// Make sure, you're using `await` in an `async` function!
await Promise.all(promises)

// all the fruits are saved in the db

console.log(
  Fruit.find({}, function (err, elements) {
  // ...
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