I'm pulling weather data in JSON format from Wundground through their API with no problems. I'm trying to store that data in MongoDB for later use. I actually get the data and am able to write it to a collection in Mongo. However, when I do a db.collection.find() it almost looks like each individual character is being saved separately rather than JSON format. Here's the code snippet that gets data and should be saving to 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);
});
});
A small excerpt of the JSON-formatted weather data:
{ current_observation: {
image: {
url: http://icons-ak.com/graphics/logo.png,
title: Weather Underground
},
display_location: {
full:My City, State,
city:My City,
I shouldn't have to parse the data before saving to Mongo should I? So what am I missing. As I said, if I output to the console all the weather data displays perfectly I just seem to be doing something wrong between Node.JS and MongoDB.
Thanks.
UPDATE***
I did try to parse str in this way with
// 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);`
That didn't seem to work either. I will look at it again.