尝试与历史聊天,我对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);
}
});
但没有成功,它会返回"空"结果,这听起来很奇怪:(
非常感谢您提供的帮助!:)
答案 0 :(得分:2)
您正在查询查询。这意味着您正在mongo游标上运行.each循环。你想要做的是通过回调传递查询。
collection.find({},function(err,doc){
//do stuff with doc and err
})
答案 1 :(得分:0)
我尝试了您的代码并且工作正常。
在doc
回调的最后一次调用中,null
为each
是正常的,表明游标已用尽(请参阅示例代码中的注释) each
的{{3}}。
我对您的代码所做的只是添加一个尾随});
,以便运行:
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
我使用insert
两次运行您的message
代码,以添加它显示的两个文档。
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);
});
});
});