Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从mongodb集合获取数据_Mongodb_Sockets_Collections_Database - Fatal编程技术网

从mongodb集合获取数据

从mongodb集合获取数据,mongodb,sockets,collections,database,Mongodb,Sockets,Collections,Database,为了从db集合中获取一些消息,我尝试了服务器端的代码: MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) { if(err) throw err; var history=""; var collection = db.collection('gt-chat'); console.log("******************************Printing

为了从db集合中获取一些消息,我尝试了服务器端的代码:

MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) {
    if(err) throw err;
    var history="";
    var collection = db.collection('gt-chat');
    console.log("******************************Printing docs from Cursor Each")
    collection.find({}, {_id: 0}).sort({$natural: 1}).limit(20).each(function(err, doc) {
        console.log(doc)
        if(doc != null) {
            console.log("Doc from Each ");
            history=history+console.dir(doc)+"\r\n";
            console.dir(doc);
        }
    });

    console.log("/////////////HISTORY//////////////////");
    console.log(history); ; // data is shown there under the shell console, all is fine !

    socket.emit('updatechat', 'SERVER', history); // should send the messages using socket
});
然后在客户端,我尝试了:

// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
    date = new Date;
    h = date.getHours();
    if (h<10) {
        h = "0"+h;
    }
    m = date.getMinutes();
    if (m<10) {
        m = "0"+m;
    }
    s = date.getSeconds();
    if (s<10) {
        s = "0"+s;
    }
    var time = h+":"+m+":"+s;
    $('#conversation').append('<b><strong>' + time + '</strong>      '+username + ':</b> ' + data +     '<br>');
});
但我不了解所有的历史。 因此,我们的目标是从mongodb集合中获取一些消息,并使用socket emit在浏览器下显示它们

在shell下,要调试,它显示:

Doc from Each { message: '<strong>12:16:27</strong><span style=\'color:#2fed7e\'><b>guibs</b>< /span><em> hum</em>' } { message: '<strong>12:16:27</strong><span style=\'color:#2fed7e\'><b>guibs</b>< /span><em> hum</em>' }
因此,数据和消息是存在的,但我无法从浏览器中读取它们。外壳上写着:“历史没有定义”!连接有什么问题?我的变量声明呢?我不明白,谢谢你的帮助

Doc from Each { message: '<strong>12:16:27</strong><span style=\'color:#2fed7e\'><b>guibs</b>< /span><em> hum</em>' } { message: '<strong>12:16:27</strong><span style=\'color:#2fed7e\'><b>guibs</b>< /span><em> hum</em>' }