2014-10-03 59 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