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

333
Vistas
Mongoose find() Method Returns No Value First Time I Run Node

The idea is very simple. I add 4 entries into 'fruits' collection inside 'fruitsDB'. When I run server.js it actually adds the list entries into database.

When I check database it says I have 4 entries [apple, kiwi, orange, banana]. however the find method which is

Fruit.find(function(err, fruits){
    if(err){
        console.log(err);
    } else {
        console.log(fruits);
} });

returns an empty array when I run server.js for the first time. If I run server.js second time and check the collections from inside MongoDB, since this is second time running new collection content shows like

[apple, kiwi, orange, banana, apple, kiwi, orange, banana]

This time find() method shows the array but only 4 of them... What I am doing wrong here?

enter image description here

Server.js:

const mongoose = require('mongoose');

main().catch(err => console.log(err));

// This section means connect to mongodb and create fruitsDB database inside that
async function main() {
    await mongoose.connect('mongodb://localhost:27017/fruitsDB');
  }

const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
});

const Fruit = mongoose.model('Fruit', fruitSchema);

//  MongoDB will automatically pluralize the collection name
// const fruit = new Fruit({
//     name: 'Apple',
//     rating: 7,
//     review: 'Pretty solid as fruit!'
// });

// Comment out this section to prevent mongoose to 
    // save fruit to fruits collection everytime you run server.js
// fruit.save();

const peopleSchema = new mongoose.Schema({
    name: String,
    age: Number
});

const People = mongoose.model('People', peopleSchema);

const people = new People({
    name: 'John',
    age: 37
});

people.save();

const apple = new Fruit({
    name: 'Apple',
    rating: 7,
    review: 'Pretty solid as fruit!'
});

const kiwi = new Fruit({
    name: 'Kiwi',
    rating: 10,
    review: 'The best fruit!'
});

const orange = new Fruit({
    name: 'Orange',
    rating: 4,
    review: 'Too sour for me!'
});

const banana = new Fruit({
    name: 'Banana',
    rating: 3,
    review: 'Weird texture!'
});

Fruit.insertMany([apple, kiwi, orange, banana], function(error){
    if(error){
        console.log(error);
    } else {
        console.log('New entries are added to the database!');
    }
});

// Read the fruits collection
Fruit.find(function(err, fruits){
    if(err){
        console.log(err);
    } else {
        console.log(fruits);
    }
});
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

find() method runs before the database has the chance to store the data.
You can store the insertMany() call in an async function with await and put your Fruit.find() after it

async function myFunc() {
    await Fruit.insertMany([apple, kiwi, orange, banana], function (error) {
        if (error) {
            console.log(error);
        } else {
            console.log('New entries are added to the database!');
        }
    });
    Fruit.find(function (err, fruits) {
        if (err) {
            console.log(err);
        } else {
            console.log(fruits);
        }
    });
}
myFunc();

Or take advantage of Promise callbacks and use .then().

myFunc().then(() => {
    Fruit.find(function (err, fruits) {
        if (err) {
            console.log(err);
        } else {
            console.log(fruits);
        }
    });
},err=> console.log(err));
about 4 years ago · Juan Pablo Isaza Denunciar

0

You have to wait for Mongoose to connect to your MongoDB server, and then you should perform all the logic. What you can do is just put all the logic in the main() function after the await mongoose.connect('mongodb://localhost:27017/fruitsDB');. That will ensure that the Mongoose connected to the MongoDB server before any DB query where executed.

const mongoose = require('mongoose');

main().catch(err => console.log(err));

// This section means connect to mongodb and create fruitsDB database inside that
async function main() {
  await mongoose.connect('mongodb://localhost:27017/fruitsDB');

  const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
  });

  const Fruit = mongoose.model('Fruit', fruitSchema);

  //  MongoDB will automatically pluralize the collection name
  // const fruit = new Fruit({
  //     name: 'Apple',
  //     rating: 7,
  //     review: 'Pretty solid as fruit!'
  // });

  // Comment out this section to prevent mongoose to 
  // save fruit to fruits collection everytime you run server.js
  // fruit.save();

  const peopleSchema = new mongoose.Schema({
    name: String,
    age: Number
  });

  const People = mongoose.model('People', peopleSchema);

  const people = new People({
    name: 'John',
    age: 37
  });

  people.save();

  const apple = new Fruit({
    name: 'Apple',
    rating: 7,
    review: 'Pretty solid as fruit!'
  });

  const kiwi = new Fruit({
    name: 'Kiwi',
    rating: 10,
    review: 'The best fruit!'
  });

  const orange = new Fruit({
    name: 'Orange',
    rating: 4,
    review: 'Too sour for me!'
  });

  const banana = new Fruit({
    name: 'Banana',
    rating: 3,
    review: 'Weird texture!'
  });

  Fruit.insertMany([apple, kiwi, orange, banana], function(error) {
    if (error) {
      console.log(error);
    } else {
      console.log('New entries are added to the database!');
    }
  });

  // Read the fruits collection
  Fruit.find(function(err, fruits) {
    if (err) {
      console.log(err);
    } else {
      console.log(fruits);
    }
  });
}
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