简体   繁体   English

将Node.js中的JSON数据存储到MongoDB

[英]Storing JSON data from Node.js to MongoDB

I'm pulling weather data in JSON format from Wundground through their API with no problems. 我正在通过他们的API从Wundground以JSON格式提取天气数据,没有任何问题。 I'm trying to store that data in MongoDB for later use. 我正在尝试将这些数据存储在MongoDB中供以后使用。 I actually get the data and am able to write it to a collection in Mongo. 我实际上得到了数据,并能够将它写入Mongo的集合中。 However, when I do a db.collection.find() it almost looks like each individual character is being saved separately rather than JSON format. 但是,当我执行db.collection.find()时,它几乎看起来像是单独保存每个单独的字符而不是JSON格式。 Here's the code snippet that gets data and should be saving to Mongo: 这是获取数据的代码片段,应该保存到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: JSON格式的天气数据的一小部分摘录:

{ "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? 我应该在保存到Mongo之前解析数据吗? 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. 正如我所说,如果我输出到控制台所有的天气数据显示完美,我似乎在Node.JS和MongoDB之间做错了。

Thanks. 谢谢。

UPDATE*** UPDATE ***

I did try to parse "str" in this way with 我确实尝试用这种方式解析“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");`

That didn't seem to work either. 这似乎也没有用。 I will look at it again. 我会再看一遍。

Yes, you need to give to your send function a JavaScript object (cf. the MongoDB native driver documentation , which it looks like you're using), but you send it a string (which is why you can concatenate it on each data event). 是的,您需要为您的send函数提供一个JavaScript对象(参见MongoDB本机驱动程序文档 ,它看起来就像您正在使用的那样),但是您发送一个字符串(这就是为什么您可以在每个data事件上连接它) )。 You'll have to convert your string to a full object using JSON.parse(str) . 您必须使用JSON.parse(str)将字符串转换为完整对象。

If you want to be sure of which data type you're dealing with, print the result of typeof str and typeof JSON.parse(str) . 如果要确定要处理的数据类型,请打印typeof strtypeof JSON.parse(str)

Edit : You have a second issue in your code. 编辑 :您的代码中有第二个问题。 The response object is actually a stream , which means it emits data when it receives it. response对象实际上是一个 ,这意味着它在收到数据时会发出数据。 This also means you can receive the data event multiple times. 这也意味着您可以多次接收data事件。 This is why you need to: 这就是您需要:

  1. Create an empty string 创建一个空字符串
  2. On each data event, concatenate the chunk you just received to the string 在每个data事件上,将刚刚收到的块连接到字符串
  3. Only try to parse it at then end, when you're sure you will not receive any more data. 当您确定不会再收到任何数据时,请尝试在最后解析它。

In the updated code snippet you gave, you tried to parse the string on the first data event, but that might be an incomplete string. 在您提供的更新的代码段中,您尝试在第一个数据事件上解析字符串,但这可能是一个不完整的字符串。

Here is the correct way to achieve this: 以下是实现此目的的正确方法:

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

Related to this issue, you also registered a listener to the end event, which is good, but you added a new listener on each data event! 与此问题相关,您还注册了一个end事件的侦听器,这很好,但您在每个data事件上添加了一个新的侦听器! Which means if you receive 5 data events, you'll call 5 times the function that will add the object to MongoDB… In the snippet above, notice I've moved the response.on('end', function() {…}) on the outside of the response.on('data') callback. 这意味着如果您收到5个数据事件,您将调用将该对象添加到MongoDB的函数的5倍...在上面的代码段中,请注意我已经移动了response.on('end', function() {…})response.on('data')回调的外部。

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);
    });
});

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM