I am trying to use nodejs and mongodb. I can enter tweets to a collection with using a function of ntwitter
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");
}
});
});
});
When I try to get the tweets from the collection I use express , nodejs and mongo and use them as below :
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);
});
});
};
In the console.log I see tweets as in this pastebin link
In the browser I get an unordered list of
:undefined
:undefined
What can I do to show tweets text ? Thanks
You're not storing the entire tweet object, just the text. So the mongodb driver sees your string as an array, hence the array-like object properties you're seeing.
Try this line:
tweetCollection.insert(data,function(error){
instead of:
tweetCollection.insert(tweet,function(error){
Or if you really just want to store the text, try something like:
tweetCollection.insert({ text: tweet },function(error){