Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a REST API With Express Modeling Data for the API Default Values in Mongoose

Marko Delgadillo
Marko Delgadillo
4,524 Points

Within ```Animal.find```, animals is undefined and therefore ```forEach``` is not running... what am I missing???

I have the code typed out just like in the example and it adds the documents into my database just fine, but since in Animal.find, animals is undefined, the forEach method isn't working and therefore not running the console.log message.... Here is my code:

```Animal.remove({}, function(err) { //clears the database to not repeat a document if (err) console.error(err) elephant.save(function(err) { if (err) console.error(err) animal.save(function(err) { if (err) console.error(err) whale.save(function(err) { if (err) console.error(err) Animal.find({ size: 'big' }, function(err, animals) { animals.forEach(animal => console.log( animal.name + ' the ' + animal.color + ' ' + ' ' + animal.type ) ) }) db.close(function() { console.log('db connection closed.') }) }) }) }) })

1 Answer

r h
r h
68,552 Points

It has to do with the db.close() running before the callback function of the animals.forEach is run. This happens if you have db.close() outside of the Animal.find() callback function. So the database is closed and therefore the retrieval from Animal.find() is undefined.

Make sure you put the db.close() after the animals.forEach but still within the callback for the Animal.find:

Animal.remove({}, () => {
    elephant.save((err) => {
      if (err) {
        console.error('save failed', err);
      } else {
        console.log("saved!");
      }
      animal.save((err) => {
        if (err) {
          console.error('save failed', err);
        } else {
          console.log("saved!");
        }
        whale.save((err) => {
          if (err) {
            console.error('save failed', err);
          } else {
            console.log("saved!");
          }
          Animal.find({"size": "big"}, function(err, animals) {
            animals.forEach(function(animal){
              console.log(animal.name + " the " + animal.color + " " + animal.type);
            });
            db.close(() => {
              console.log("db connection closed");
            });
          });

        });

      });

    });
  });

Thank you so much.