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

160
Vistas
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 Respuestas
Responde la pregunta

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