Waiting MongoClient for remote db to answer


I have 2 functions in which one return query for publication, and the other which is summarized as below:

var MongoClient = require(‘mongodb’).MongoClient;
var url = MongoURL+"/" + db;
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log(“Connected correctly to server”);
const database = client.db(db);
let query = findDocuments(database, ‘anny’, function() {
Basically, it returns all documents in the collection anny. The problem is my first function does not wait for the the other function to find and return the documents. What will be the optimal way make my function wait till the answer is ready?


Is this a Meteor question? That code example is not standard Meteor.

In Meteor, your code would basically become:

const Anny = new Mongo.Collection('anny');
const Result = Anny.find();

All waiting managed for you.


yes that is true, if not considering the fact that I am connecting to remote dbs. After some time I started worrying about number of connections and tried to close them whenever I do not use. NPM functions give such an opportunity. https://www.npmjs.com/package/mongodb But again coming to my initial question, the documents comes in async way and I want to have control over them.


Then you either need to strictly observe the callbacks, or rewrite your code to use async/await. The MongoDB npm library returns Promises if you don’t use callbacks, so this is really easy. Your findDocuments function also needs to return a Promise (which may also be easy if it just wraps a collection.find()). Then it’s just a case of awaiting each Promise. Wrap the whole lot in a try/catch within an async function and your good to go.


All right. Thanks for the answer! I’ll definitely try.