orlandov / node-mongodb

mongodb bindings for node.js
163 stars 14 forks source link

It's not calling my callbacks #7

Open nickretallack opened 14 years ago

nickretallack commented 14 years ago

The tests pass, and everything works if it happens to occur inside a listener like so:

mongo.addListener("connection", function () { 
    mongo.getCollection('widgets').count(null, function(count) { sys.puts(count) })
})

However, when I try to do this in any other context, the callback never happens. For example, if I set up a server like this, and hit it, nothing is printed to the console.

var port = 8000
http.createServer(function (req, res) {
    mongo.getCollection('widgets').count(null, function(count){
        sys.puts("found stuff!")
    })
}).listen(port)

In fact, even if I put this createServer stuff inside of a connection callback, it still doesn't work.

caged commented 14 years ago

I think I've had a similar issue occur when trying to use node-mongodb with the Express nodejs framework. Unless I'm misunderstanding the code, node-mongodb assumes everything will live inside the connection callback and the connection happens in the same process as the query/getCollection code.

For instance, this doesn't work:

mongodb = require('mongodb')
mongo = new mongodb.MongoDB()

http.createServer(function (req, res) {
  sys.puts('Server created...')
  mongo.addListener("connection", function (connection) {  
    sys.puts('Mongodb connected...')
    mongo.getCollection('messages').count(null, function(count){
        sys.puts(count)
    })
  })
}).listen(8000)

mongo.connect({
    hostname: '127.0.0.1',
    port: 27017,
    db: 'mydatabase'
})

However, if we moved the mongo.connect line at the bottom inside the createServer callback, everything works as expected.

I think one way to solve this would be to take an approach like the node-mongodb-native (similar name, different project) project so queries would work independent of the initial connection.

mongo.open(function(db) { db.getCollection... })