Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!