Socket.io 使用 mongoDB 文档发出 [object Object]

Socket.io emitting [object Object] with mongoDB document

首先祝大家感恩节快乐!我希望每个人都喜欢他们将要吃的所有食物!我知道我会..

任何人,

我正在尝试在我的 mongoDB 集合中查询已插入的最新文档并将其发送给客户端。然而,网页上唯一显示的是 [object Object] 而不是存储在文档中的数据。当我 console.log 发送数据时,它显示:

Object {newData: Array[1]}
newData: Array[1]
0: Object_id: "564f8b8cfa74e4daab1543ca"
ambientAtTrackTempSensor: "-"
date: "10/09/2015"
dewPoint: "56"
humidity: "63.0"
pressure: "29.258"
solar: "397"
temp: "80.1"
time: "17:00"
trackTemp: "-"
windBearing: "222"
windGust: "7.0"
windSpeed: "6.0"
__proto__: Object
length: 1
__proto__: Array[0]
__proto__: Object

所以数据就在那里,我想我只是没有正确访问它。

这是我的代码:

服务器:

var io = require('socket.io').listen(server);

MongoClient.connect(dbUrl, function(err, db) {
  if (err) {
    console.log('Failed to connect to mongoDB database.');
  } else {
    console.log('Succesfully connected to mongoDB database.');
  };

io.sockets.on('connection', function(socket) {
// send data to client
  var collection = db.collection('track_weather');
  collection.find().sort({_id:-1}).limit(1).toArray(function(err, docs) {
    console.log(docs);
    socket.emit('message', {'newData': docs});
  });
 });
});

客户:

<body>

<script>
  var socket = io.connect();

  socket.on('message', function(data) {
    $('#newData').text(data.newData);
    console.log(data);
  });
</script>

<div id="newData"></div>

</body>

如有任何帮助,我们将不胜感激!我对这一切都很陌生:)

您必须将对象字符串化才能显示它,否则 javascript 将只显示类型(此处为 [object Object])。

$('#newData').text(JSON.stringify(data.newData));