2014-10-03 72 views
0

我想使用nodejs和mongodb。我可以進入鳴叫集合使用的ntwitter如何使用流API的nodejs和mongodb列出tweet文本

twit.stream('statuses/filter', {'track':'dio'}, function(stream) { 
    stream.on('data', function (data) { 
    var tweet = data.text; 
    tweetCollection.insert(tweet,function(error){ 
      if(error) { 
       console.log("Error", error.message); 
      } else { 
       console.log("Inserted into database"); 
      } 
    }); 
    }); 
}); 

的功能。當我試圖從我用快遞,的NodeJS和蒙戈收集的鳴叫和如下使用它們:

app.get('/', function(req, res){ 
    var content = fs.readFileSync("template.html"); 

    getTweets(function(tweets){ 

     console.log(tweets); 
     var ul = ''; 
     tweets.forEach(function(tweet){ 
      ul +='<li><strong>' + ":</strong>" + tweet["text"] + "</li>"; 
     }); 
     content = content.toString("utf8").replace("{{INITIAL_TWEETS}}", ul); 
     res.setHeader("Content-Type", "text/html"); 
     res.send(content); 
     }); 

}); 
db.open(function(error) { 
    console.log("We are connected " + host + ":"+ port); 

    db.collection("tweet",function(error, collection){ 
      tweetCollection = collection;    
    }); 
}); 
function getTweets(callback) { 
    tweetCollection.find({}, { "limit":10, "sort":{"_id":-1} } , function(error, cursor){ 
      cursor.toArray(function(error, tweets){ 

       callback(tweets); 
      }); 
    }); 
}; 

在我的console.log看到微博在本pastebin link

在瀏覽器中,我得到的

:undefined 
:undefined 
一個無序列表

如何顯示推文文字? 謝謝

回答

1

你沒有存儲整個tweet對象,只是文本。因此,mongodb驅動程序將您的字符串視爲一個數組,因此您看到的是類似數組的對象屬性。

試試這個行:

tweetCollection.insert(data,function(error){ 

代替:

tweetCollection.insert(tweet,function(error){ 

或者,如果你真的只想存儲文本,你可以試試:

tweetCollection.insert({ text: tweet },function(error){ 
+0

感謝萬次。它按預期工作。 – ytsejam 2014-10-03 17:21:57