0

I'm just getting into node and mongodb and came across the first obstacle.

I'm walking through a tutorial where the code looks something like this:

var db = new mongo.Db("database", new mongo.Server(host, port, {}));
db.open(function(error){
  db.collection("user", function(err, collection){
    collection.find({"id":"1"}, function(error, cursor){
      cursor.toArray(function(err, users){
        if(users.length == 0){
          console.log("no such user");
        } else if {
          console.log("user found: ", users[0]);
        }
     });
   });
 });

However the code failed to work saying that users is null. (I do have a code where it inserts entries) Anyway, while trying to figure out what's going on, I've come across the documentation where it uses a synchronous pattern for find instead of using callback to retrieve cursor. The code goes something like this:

var cursor = collection.find({"id":"1"});

In fact, I cannot find anywhere in the documentation where it mentions a usage of find with a callback that returns a cursor. I am really confused. Is the tutorial outdated? And what is wrong with this code?

Vlad
  • 8,038
  • 14
  • 60
  • 92

1 Answers1

0

If users is null, then it's likely that err is indicating what the problem is. Add an if (err) path to your code to log err when it's set.

find can work in both ways that you describe. The callback parameter is optional and if you don't provide it you can use the cursor that's returned instead. See the docs: link.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471