refactor
refactor

Reputation: 15044

Connecting to MongoDB from Node.js causes Node to hang

Below is my code in app.js file. When I execute this code it gets connected to MongoDB and displays 'Connected to DB' message.

But once the message gets displayed I was expecting the program to end; instead the program continues to run.

Why does the program continues to run and not end after printing the text?

const mongodb = require('mongodb');
const co = require('co');

const MongoClient = mongodb.MongoClient;
const url = "mongodb://localhost:27017/test9";

co(function *() {
    db = yield MongoClient.connect(url);
    console.log('Connected to DB');
});

Upvotes: 0

Views: 273

Answers (1)

robertklep
robertklep

Reputation: 203241

Because you're not closing the connection, Node has no idea that you're done with it and it will remain running.

When you close it, the process will exit properly:

co(function *() {
  let db = yield MongoClient.connect(url);
  console.log('Connected to DB');
  yield db.close();
});

Upvotes: 1

Related Questions