0

Hello i'm trying to fetch some partner names from my mongodb database and put them into a list of variables. But it for some reason loses it's definition when I try to export it. What's going on?

This is the first file.

///// mongodb.js /////

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const findDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('partners');
  // Find some documents
  collection.find({}).toArray(function(err, docs) {
    assert.equal(err, null);
    callback(docs);
  });
};

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'yarle';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected succesfully to Database");

  const db = client.db(dbName);

  findDocuments(db, function(docs) {
    module.exports = {
      partner1: console.log(docs[0]['partner_name']),
      partner2: console.log(docs[1]['partner_name']),
      partner3: console.log(docs[2]['partner_name']),
    };
    client.close();
  });
});

//console.log(Object.keys(partners[0][0]));

And this is the end file.

///// Endfile.ts /////
import { Request, Response } from 'express';
import { PartnersList } from './data.d';

var partners = require( './mongodb.js');

console.log(partners.partner1);

const titles = [
  partners.partner1,
  partners.partner2,
  partners.partner3,
];
  • Does this answer your question? [What is the difference between synchronous and asynchronous programming (in node.js)](https://stackoverflow.com/questions/16336367/what-is-the-difference-between-synchronous-and-asynchronous-programming-in-node) – Guillaume Cretot-Richert Feb 11 '20 at 15:26
  • @GuillaumeCretot-Richert Not really I still would have no clue how I'd have to fix this. The problem is that I have to query MongoDB in this way because it will throw me an error otherwise. I'm using Ant Design with NodeJS and Umi btw. – Nick van Raaij Feb 11 '20 at 15:45

1 Answers1

1

Your problem is not with module.exports, it's with asynchronous programming. When you call MongoClient.Connect, the code in your callback does not get executed synchronously. It gets executed some time in the future. You have no control over when that happens.

The same thing is true of the findDocument callback.

Programming asynchronously is a little trickier, but you will have to learn it to write modern javascript. Asynchrony is a central tenet of nodejs. Read on it, learn examples, and your problem will become clear.

Instead of exporting the values of partner1, 2 and 3, export a function with a callback. This new function can call MongoClient.Connect, passing down the callback. Endfile.ts can now call your newly created asynchronous function and assign the titles array in the callback.

Like this:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const findDocuments = function (db, callback) {
  // Get the documents collection
  const collection = db.collection('partners');
  // Find some documents
  collection.find({}).toArray(function (err, docs) {
    assert.equal(err, null);
    callback(docs);
  });
};

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'yarle';

module.exports.getPartners = (callback) {

  // Use connect method to connect to the server
  MongoClient.connect(url, function (err, client) {
    if (err) {
      callback(err);
      return;
    }
    console.log("Connected succesfully to Database");

    const db = client.db(dbName);

    findDocuments(db, function (docs) {
      const partners = {
        partner1: docs[0]['partner_name'],
        partner2: docs[1]['partner_name'],
        partner3: docs[2]['partner_name']
      };
      callback(null, partners);
      client.close();
    });
  });

}

and this

import { Request, Response } from 'express';
import { PartnersList } from './data.d';

var mongoClient = require('./mongodb.js');
mongoClient.getPartners(function (err, partners) {
  assert.equal(null, err);
  const titles = partners;
});