为什么我得到新数据,但node.js不发送数据

Why do I get the new data but node.js does not send the data?

本文关键字:数据 node js 新数据 为什么      更新时间:2023-09-26

我使用以下代码在 mongo 数据库中获取新插入并将其发送到 html 文件:

mongo.MongoClient.connect (uristring, function (err, db) { 
        db.collection ("speed", function (err,collection) {
        collection.isCapped(function (err, capped) { 
        if (!capped) {
        console.log (collection.collectionName + " is not a capped collection");
        }
        else
        {
          var cursorOptions = {
          tailable: true,
          awaitdata: true,
          numberOfRetries: -1
        };
        var stream = collection.find({},{value:1,_id:0},cursorOptions).sort({$natural: -1}).stream();
        stream.on('data', function(document) {
          io.sockets.on('connection', function(socket){
          socket.emit('message', {'message': document});
        });
        });
        }
        });
    });
});

在客户端:

var socket = io.connect('/');
  var myValue = [];
  socket.on('message',function(data){
    console.log(data);
    myValue.push(data.message.value);

当我第一次读取数据时它工作正常,但是当我在服务器运行时插入新数据时,数据显示在服务器中但不发送到客户端。

 stream.on('data', function(document) {
            socket.emit('message', {'message': document});
          io.sockets.on('connection', function(socket){
          socket.emit('message', {'message': document});
        });
        });

在你的第一个socket.emit(),你指的是哪个套接字? 删除您的第一个 socket.emit 将解决问题。

stream.on('data', function(document) {
          io.sockets.on('connection', function(socket){
          socket.emit('message', {'message': document});
        });
        });

或者按如下所示更改代码也应该可以正常工作。

io.sockets.on('connection', function(socket){
              stream.on('data', function(document) {
                    socket.emit('message', {'message': document});
                    });
                });