将 JSON 数据从 Node.js 存储到 MongoDB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19846462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing JSON data from Node.js to MongoDB
提问by Godfried
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:
我正在通过他们的 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");
});
});
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? 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.
我不应该在保存到 Mongo 之前解析数据吗?那我错过了什么。正如我所说,如果我将所有天气数据输出到控制台,所有天气数据都能完美显示,我似乎只是在 Node.JS 和 MongoDB 之间做错了。
Thanks.
谢谢。
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.
那似乎也不起作用。我会再看一遍。
回答by Paul Mougel
Yes, you need to give to your sendfunction 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 dataevent). You'll have to convert your string to a full object using JSON.parse(str).
是的,您需要为您的send函数提供一个 JavaScript 对象(参见MongoDB 本机驱动程序文档,它看起来像是您正在使用的),但是您向它发送一个字符串(这就是您可以在每个data事件上连接它的原因)。您必须使用 将字符串转换为完整对象JSON.parse(str)。
If you want to be sure of which data type you're dealing with, print the result of typeof strand typeof JSON.parse(str).
其中,如果你想以确保数据输入你处理的,打印的结果typeof str和typeof JSON.parse(str)。
Edit: You have a second issue in your code. The responseobject is actually a stream, which means it emits data when it receives it. This also means you can receive the dataevent multiple times. This is why you need to:
编辑:您的代码中有第二个问题。该response对象实际上是一个流,这意味着它在接收到数据时发出数据。这也意味着您可以data多次接收该事件。这就是为什么您需要:
- Create an empty string
- On each
dataevent, concatenate the chunk you just received to the string - Only try to parse it at then end, when you're sure you will not receive any more data.
- 创建一个空字符串
- 在每个
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 endevent, which is good, but you added a new listener on each dataevent! 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.
与此问题相关,您还为该end事件注册了一个侦听器,这很好,但是您为每个data事件添加了一个新侦听器!这意味着如果您收到 5 个数据事件,您将调用 5 次将对象添加到 MongoDB 的函数……在上面的代码片段中,请注意我已将 移动response.on('end', function() {…})到response.on('data')回调的外部。
回答by Ankit Jain
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

