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

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

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 Report

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