使用带有节点js的mongodb来创build一个具有历史logging的聊天系统

试图与历史聊天,我与mongodb和节点js几个问题是清楚的:我可以保存一个新的消息在一个mongodb集合的代码部分:

MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) { if(err) throw err; var collection = db.collection('gt-chat'); collection.insert({message:mess}, function(err, docs) { console.log("//////////////\r\n mess insertion :"+mess); collection.count(function(err, count) { console.log(format("count = %s", count)); }); }); 

但我不能读从MongoDB 我试过的东西

 MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) { if(err) throw err; var collection = db.collection('gt-chat'); console.log("Printing docs from Cursor Each") // Find all records. find() returns a cursor // Print each row, each document has an _id field added on insert // to override the basic behaviour implement a primary key factory // that provides a 12 byte value collection.find().each(function(err, doc) { console.log(doc); if(doc != null) { console.log("Doc from Each "); console.dir(doc); } }); 

但没有成功,它返回“空”作为结果,这听起来奇怪:(

非常感谢您的帮助!:)

我试过你的代码,它工作正常。

在最后一次调用eachcallback时, docnull ,这是光标已经耗尽的一个指示(请参阅each 文档的示例代码中的注释)。

我对你的代码做的只是添加一个尾部}); 所以它会运行:

 MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) { if(err) throw err; var collection = db.collection('gt-chat'); console.log("Printing docs from Cursor Each") collection.find().each(function(err, doc) { console.log(doc); if(doc != null) { console.log("Doc from Each "); console.dir(doc); } }); }); 

哪些产出:

 Printing docs from Cursor Each { _id: 5480e2667baf089e0b055c7a, message: 'The quick brown fox jumps over the lazy dog' } Doc from Each { _id: 5480e2667baf089e0b055c7a, message: 'The quick brown fox jumps over the lazy dog' } { _id: 5480e293744a68a90b3f44fb, message: 'The quick brown fox jumps over the lazy dog' } Doc from Each { _id: 5480e293744a68a90b3f44fb, message: 'The quick brown fox jumps over the lazy dog' } null 

我使用该message运行了两次insert代码,以添加它显示的两个文档。

 var mess = 'The quick brown fox jumps over the lazy dog'; MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) { if(err) throw err; var collection = db.collection('gt-chat'); collection.insert({message:mess}, function(err, docs) { console.log("//////////////\r\n mess insertion :"+mess); collection.count(function(err, count) { console.log("count = %s", count); }); }); }); 

您链接到查询。 这意味着你正在mongo游标上运行.each循环。 你想做的是传递查询callback。

 collection.find({},function(err,doc){ //do stuff with doc and err })