2013-10-31 121 views
0

我的问题是我无法从我的mongodb数据库中检索数据......而且我不知道为什么。无法从集合中检索数据

我可能做错了什么,这里有一个小小的赌注,它不起作用。

var Db   = require('mongodb').Db, 
    Server  = require('mongodb').Server; 


var db = new Db('akemichat', new Server('localhost', 27017), {w:1}); 
db.open(function (err, p_db) { 
    db = p_db; 
}); 


db.collection('rooms', function (err, collection) { 
    if (!err) { 
     collection.find().toArray(function(err, items) { 
      items.forEach(function(room) { 
       console.log('hello'); // Never call... 
      }); 
     }); 
    } else { 
     console.log(err); 
    } 
}); 

请注意,我在我的数据库有数据显示如下

➜ akemichat git:(master) ✗ mongo 
MongoDB shell version: 2.4.7 
connecting to: test 
> use akemichat 
switched to db akemichat 
> db.rooms.find() 
{ "name" : "home", "_id" : ObjectId("527008e850305d1b7d000001") } 

感谢您的帮助!

注意:示例程序永远不会结束,我也不知道为什么......也许是因为连接永远不会关闭,但如果我叫db.close()toArray回调,它永远不会被调用,因为回调从未happends。

+1

试着将你的集合'find'移动到''open''事件回调的回调函数中。 – WiredPrairie

回答

1

节点中的很多东西都是异步的。尝试读取收藏集后,您的连接已打开。

您应该在知道确切连接后查询集合。 Down and dirty:

var Db   = require('mongodb').Db, 
    Server  = require('mongodb').Server; 


var db = new Db('akemichat', new Server('localhost', 27017), {w:1}); 
db.open(function (err, p_db) { 
    db = p_db; 

    db.collection('rooms', function (err, collection) { 
     if (!err) { 
      collection.find().toArray(function(err, items) { 
       items.forEach(function(room) { 
        console.log('hello'); // Never call... 
       }); 
      }); 
     } else { 
      console.log(err); 
     } 
    }); 
}); 

我在本地运行并接收到“hello”消息。此外,您的脚本永远不会完成,因为节点进程将运行直到它关闭或崩溃。这是设计。这也意味着你不必打开和关闭你的mongo连接。您可以在应用程序启动时打开连接,并在关闭应用程序时关闭它。

+0

非常感谢。 – Nek