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

334
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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