简体   繁体   English

即使使用 module.exports,NodeJS 和 MongoDB 也会丢失变量的定义

[英]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.您好,我正在尝试从我的 mongodb 数据库中获取一些合作伙伴名称并将它们放入变量列表中。 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 .您的问题不在于 module.exports,而在于异步编程 When you call MongoClient.Connect, the code in your callback does not get executed synchronously.当您调用 MongoClient.Connect 时,您的回调中的代码不会同步执行。 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. findDocument 回调也是如此。

Programming asynchronously is a little trickier, but you will have to learn it to write modern javascript.异步编程有点棘手,但您必须学习它才能编写现代 javascript。 Asynchrony is a central tenet of nodejs.异步是 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.不是导出 partner1、2 和 3 的值,而是导出带有回调的函数。 This new function can call MongoClient.Connect, passing down the callback.这个新函数可以调用 MongoClient.Connect,传递回调。 Endfile.ts can now call your newly created asynchronous function and assign the titles array in the callback. Endfile.ts 现在可以调用您新创建的异步函数并在回调中分配 titles 数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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