0

I am running a quick little nodejs script to find documents in one collection and insert them into another collection but on the same DB. I came up with this guy, but it has no way to close because I think its running open or async?

I have tried placing the db.close() in various places and tried mongoClient.close(). No luck which had me thinking about trying to force a timeout for the async call. Added a connection Time out but it did not have the desired behaviour.

var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
const async = require("async");

// Connection URL 
var url = 'mongodb://localhost:27017/sourceDB';

// Use connect method to connect to the Server 
MongoClient.connect(url,{connectTimeoutMS: "5"}, (err, db) => {


db.collection('source.collection', function(err, col) {
assert.equal(null, err);

col.find().forEach(function (data) {
console.log(data);

db.collection('destination.collection').insertOne(data, function(err, res) {
assert.equal(null, err);
});

console.log("Moved");

});
});
});

The script does well and picks up the collection and inserts, but the connection remains open.

Dzmitry Bahdanovich
  • 1,735
  • 2
  • 17
  • 34

1 Answers1

0

It is not recommended to explicitly close the connection as shown by this SO thread.
Rather, allow the client library to manage the connection for you.

Victor Ian
  • 1,034
  • 13
  • 26
  • I read that and it basically comes down to a manual stop. Run a cron which runs the js then do a manual close, then repeat. I would think this would not be a healthy situation for the DB. And you would want a clean close. – Barnettej May 31 '19 at 03:52