使用MongoDB和Node JS制作一个带有历史记录的聊天系统

using mongodb with node js to make a chat system with history

本文关键字:一个 历史 记录 系统 聊天 Node MongoDB JS 使用      更新时间:2023-09-26

试图与历史记录聊天,我在mongodb和node 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);
    }
});

但是没有成功,它返回" null"作为结果,这对我来说听起来很奇怪:(

提前感谢您对此的帮助:)

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

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

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

doc在最后一次调用each回调时null是正常的,以指示游标已用尽(请参阅文档示例代码中的注释以获取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);
        });
    });
});