[英]Storing data stream from POST request in GridFS, express, mongoDB, node.js
[英]Storing JSON data from Node.js to 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://icons-ak.com/graphics/logo.png",
"title": "Weather Underground"
},
"display_location": {
"full":"My City, State",
"city":"My City",
我應該在保存到Mongo之前解析數據嗎? 所以我錯過了什么。 正如我所說,如果我輸出到控制台所有的天氣數據顯示完美,我似乎在Node.JS和MongoDB之間做錯了。
謝謝。
UPDATE ***
我確實嘗試用這種方式解析“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本機驅動程序文檔 ,它看起來就像您正在使用的那樣),但是您發送一個字符串(這就是為什么您可以在每個data
事件上連接它) )。 您必須使用JSON.parse(str)
將字符串轉換為完整對象。
如果要確定要處理的數據類型,請打印typeof str
和typeof JSON.parse(str)
。
編輯 :您的代碼中有第二個問題。 response
對象實際上是一個流 ,這意味着它在收到數據時會發出數據。 這也意味着您可以多次接收data
事件。 這就是您需要:
data
事件上,將剛剛收到的塊連接到字符串 在您提供的更新的代碼段中,您嘗試在第一個數據事件上解析字符串,但這可能是一個不完整的字符串。
以下是實現此目的的正確方法:
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個數據事件,您將調用將該對象添加到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);
});
});
參考來自: http : //code.runnable.com/UW3ef2Tkq498AABE/insert-a-record-in-mongodb-using-mongodb-native-for-node-js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.