0

I am using twitter API in my code and mongodb. The is reflecting the correct output in database, but it's not terminating. I guess the problem is with db.server.find({id:myid},cb); statement in code below. However, I don't know how to work it out.

var Twit = require('../lib/twitter'),
    conf = require('../config1');
var myid;
var twit = new Twit(conf);
var databaseUrl = "mydb2"; // "username:password@example.com/mydb"
var collections = ["server", "followers"];
var db = require("mongojs").connect(databaseUrl, collections);
twit.get('account/verify_credentials', function (err, reply) {
    myid = reply.id;

    function addToServer(myid, cb) {
        db.server.find({
            id: myid
        }, cb);
    };

    addToServer(myid, function (err, resp) {
        if (err) {
            console.log("err");
        } else if (resp.length > 0) {
            console.log("My Id present in server present");
        } else {
            console.log("New to the app.So updating server  ");
            db.server.insert({
                id: myid
            });
            db.followers.insert({
                id: myid,
                following: []
            })
        }
    });
});

P.S: This is a part of my code , I have also used process.exit(0) function, but still no help.

juanpaco
  • 6,303
  • 2
  • 29
  • 22
jayesh hathila
  • 279
  • 1
  • 6
  • 14

1 Answers1

0

I think your issue is related to this: https://github.com/mafintosh/mongojs/issues/15.

Here's a gist. If I call db.close() the program exists, and if I don't, it doesn't. So process.on('exit') must not be the right place to call it.

But the issue is that that you have a persistent tcp connection open to the DB, and as long as that's running, the script won't shut down.

Is this a run-once script, or do you need to keep this thing running?

EDIT:

Since the script only needs to run once, I'd use callbacks on your 2 database queries and close the database down in the last callback.

juanpaco
  • 6,303
  • 2
  • 29
  • 22
  • No I just have to run it once. – jayesh hathila Jan 14 '14 at 21:52
  • This is the complete code : http://pastebin.com/GJNJdfUw . Can you please help me in this code. – jayesh hathila Jan 14 '14 at 22:01
  • Hmmm... yeah, with that structure knowing where to put the db.close would be tough. Basically, you just need to figure out when you're done running queries and then close your db connection int hat last callback. https://github.com/caolan/async is useful for this. – juanpaco Jan 14 '14 at 22:10