简体   繁体   中英

NodeJS and MongoDB losing the definition of a variable even with module.exports

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,
];

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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM