2

I'm going through learnyoumongo and I'm stuck on part 3. Basically a test database is included in the challenge, it is full of parrots, and the goal is to select the parrots whose age is greater than the input. I'm getting a weird error and google is full of mongo 2.x solutions to not exactly the same problem and I'm using mongo 3.0

This is the javascript code:

var mongo = require('mongodb').MongoClient;
var parsedInput = parseInt(process.argv[2]);
var results;

mongo.connect('mongodb://localhost:27017/learnyoumongo', function(err, db){
    results = db.collection('parrots').find({ age: { $gt: parsedInput } } ).toArray(function(err, doc) //find if a value exists
    {
        if(doc) //if it does
        {
            console.log(doc);
        }
        else{
            console.log(err);
        }
    });
    //console.log(results);
    db.close();
});

This is the weird error message:

PS C:\git\learnyoumongo> node .\test.js { [MongoError: server localhost:27017 sockets closed] name: 'MongoError', message: 'server localhost:27017 sockets closed' }

I tried restarting mongo, but I'm still not able to pull any of the 'parrots' data out. Even with just find({})

J-Dizzle
  • 3,176
  • 6
  • 31
  • 49
  • Get rid of the `db.close()` and stop following documentation examples so literally. ( and it is "inside" the callback of all the examples anyway ) – Blakes Seven Jul 29 '15 at 12:10
  • It's meant to. But the other point here is you are calling it in the wrong place. Understand asynchronous functions. – Blakes Seven Jul 29 '15 at 12:23
  • possible duplicate of [When to close MongoDB database connection in Nodejs](http://stackoverflow.com/questions/8373905/when-to-close-mongodb-database-connection-in-nodejs) – Blakes Seven Jul 29 '15 at 12:25

1 Answers1

3

The problem was two pronged - The main issue was I was expecting to be able to run the query with node test.js, and see the results from the parrots collection. But learnyoumongo has atomic tests, meaning they clear the database entirely before and after, so the only way to test was learnyoumongo test.js, and I kept getting an empty result set running the node command.

The other issue was with db.close(), you can't just call db.open and then db.close, because open is async and it would close right after opening, hence the sockets closed error. So you put db.close in the toArray function, or in any other callback of db.open

J-Dizzle
  • 3,176
  • 6
  • 31
  • 49