Home > Blockchain >  Can not model.find the documents I have just saved into my mongoose
Can not model.find the documents I have just saved into my mongoose

Time:12-04

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

CodePudding user response:

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) {
  // ...
  • Related