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

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

Ryan Holm
Ryan Holm
57,502 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");
            });
          });

        });

      });

    });
  });