Mongolab nodejs拓扑被破坏 [英] Mongolab nodejs topology destroyed

查看:81
本文介绍了Mongolab nodejs拓扑被破坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用nodejs与twitter连接。我正在尝试在mongolab mongodb数据库中记录一些重要的公共用户数据。由于某种原因,我不断得到拓扑破坏错误我不太清楚为什么会这样。

I have been interfacing with twitter using nodejs. I'm trying to log some important public user data in a mongolab mongodb database. For some reason I keep getting a "topology destroyed error" I'm not quite sure why this is.

var Twitter = require('twitter');
var mongodb = require('mongodb');

var accounts = ['@zaynmalik',
'@ZooeyDeschanel'];

var client = new Twitter({
  consumer_key: 'key',
  consumer_secret: 'secret',
  access_token_key: 'key',
  access_token_secret: 'secret'
});

var MongoClient = mongodb.MongoClient;
var url = "mongodb://user:pass@mongolab.com:numbers/db";

MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
  } else {
    //HURRAY!! We are connected. :)
    console.log('Connection established to database');

    var collection = db.collection('accounts');

    for(var i = 0; i < accounts.length; i++){
        client.get('users/show', {screen_name: accounts[i]}, function(error, tweets, response){
          if(error) console.log(error);
              var account = {'screen_name': accounts[i], 'id': tweets.id};
              collection.insert(account, {w:1}, function(err, result) {console.log(err);});
              //collection.insert(account);
              console.log(tweets.id);  // Raw response object. 
        });

}

    db.close();
  }
});

如您所见,程序建立了与数据库的连接。定义集合,然后遍历许多Twitter帐户并记录相关信息。 twitter请求成功,mongodb可以处理简单的请求。如果您对我收到此回复的原因有任何想法,请回答。

As you can see the program establishes a connection to the database. Defines the collection and then iterates through a number of twitter accounts and logs pertinent information. The twitter requests are successful and the mongodb works with simple requests. If you have any ideas about why I'm getting this response please answer.

推荐答案

我有类似的问题,您的数据库连接得到了在你完成对twitter的所有请求并插入数据之前关闭。

I had similar problem, your database connection gets closed before all of your requests to twitter are done and data inserted.

我最终向我的函数发送回调,就像他们在文档中那样。

I ended up sending callback to my function like they do it in documentation.

https://github.com / mongodb / node-mongodb-native #insert-a-document

您可以在插入完成后看到他们调用回调(结果);

You can see after insertion is done they call callback(result);

这只是一个匿名函数,它调用 db.close()

And that is just anonymous function that calls db.close()

以下是一些其他可能帮助您打开/关闭数据库连接的链接

Here are some other links that might help you out with opening/closing db connections

何时关闭MongoDB数据库连接Nodejs

为什么不建议在Node.js代码中的任何地方关闭MongoDB连接?

保持打开MongoDB数据库连接

希望它有所帮助!

这篇关于Mongolab nodejs拓扑被破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆