mikemaccana
mikemaccana

Reputation: 123238

Node MongoDB: connection method callbacks never fire

I am copying an example literally from MongoDB Node documentation (well almost literally, MongoDB's official documentation hasn't been updated to match the recommendation to use MongoClient, so I'm using MongoClient).

createcollection()'s callback never runs. I've had similar problems with other connection methods, eg, find(), findAndModify().

Copied straight of out the unit test:

mongodb.MongoClient.connect(URL, function(err, db){
  // Establish connection to db
  log(1)
  assert.equal(null, err);

  // Grab a collection without a callback no safe mode
  var col1 = db.collection('test_correctly_access_collections');

  // Grab a collection with a callback but no safe operation
  db.collection('test_correctly_access_collections', function(err, col2) {
    log(2)
    assert.equal(null, err);

    // Grab a collection with a callback in safe mode, ensuring it exists (should fail as it's not created)
    db.collection('test_correctly_access_collections', {strict:true}, function(err, col3) {
      log(3)
      assert.ok(err != null);

      // Create the collection
      db.createCollection('test_correctly_access_collections', function(err, result) {
        log(4)
        // NEVER RUNS
      });
    });
  });
})

From other reading, I hear that MongoDB will queue queries if the connection is broken or slow. But connect() worked fine, my DB is localhost and has <2Kb of documents.

My question is:

EDIT: The code will work exactly one time per URL. Subsequent attempts to run the same code with the same URL will always fail. Changing the URL will work again, once per URL.

Upvotes: 3

Views: 1062

Answers (1)

mikemaccana
mikemaccana

Reputation: 123238

This was occurring because node-mongodb-native, the current 'stable' MongoDB driver, silently wraps and throws away all exceptions, including anything launched from a callback, no matter how many scopes down.

See https://groups.google.com/forum/#!topic/node-mongodb-native/AZewJaX4YuE

The solution is to use the unstable 1.3.18 series mongodb package until 1.4 (which fixes the problem permanently) is stable.

Upvotes: 2

Related Questions