![](/img/trans.png)
[英]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.