导出的变量未定义,而函数在node js中导出

exported variables got undefined while functions get exported in node js

本文关键字:node js 函数 变量 未定义      更新时间:2023-09-26

我正在创建使用mongodb的nodejs应用程序。

我连接到mongodb只有一次。我想在所有其他api中使用db,以实现连接池。

我有以下代码mongodb连接:

var mongodb = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var db;
var mongoUrl = "mongodb://localhost:27017/testDB";
/**
 * Connects to the MongoDB Database with the provided URL
 */

exports.connect = function(callback){
    if(!db){
        MongoClient.connect(mongoUrl, function(err, _db){
            if (err) { throw new Error('Could not connect: '+err); }
            db = _db;
            console.log(db);
            connected = true;
            console.log(connected +" is connected?");
            callback(db);
        });     
    }else{
        console.log("Not connected tis time as I am already connected");
        callback(db);
    }
};

exports.db = db;

当服务器从app.js启动时,我只调用connect一次。当调用signin, register等其他api时,它们应该简单地使用导出的db。

所以我的api调用将类似于(请忽略api调用中的语法错误:D):

var mongo  = require('./mongo');
collection = mongo.db.collection("testCollection");
// Here mongo.db id undefined
collection.findOne({"name":"John"}, function(err, result){
   // Do your stuff with result here
});

从其他stackoverflow的帖子,我尝试了一些像蒙古。js的

module.export{
db: db,
connect : function(callback){
  //function code goes here
}
}

但我仍然得到mongo.dbundefined如何访问其他文件中的mongodb .db ?由于

发生这种情况的原因是,因为connect覆盖模块中的dbexports.db=db;不是在调用connect函数之后执行的,而是在执行模块导入时执行的。

因此,当您调用connect时,db被设置为另一个变量,但该变量未在外部公开。

最近没有做太多的JS,但是这个应该可以了:

module.exports = new mongobj();
function mongobj() {
   this.db = null;
   this.connect = function(callback) { /* your connect code set mongobj.db */
      this.db = /* new value */ ;
   }
}

当您导入模块时,您将获得对象。访问对象的db属性将始终暴露由模块的connect函数设置的最新db值。

var mongo = require('yourmodule');
// mongo.db is null
mongo.connect(some callback);
// mongo.db is set

此连接添加到主脚本文件中…

var mongodb = require('mongodb');
var mongodb = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var mongoUrl = "mongodb://localhost:27017/testDB";

ObjectId = module.exports = require("mongojs").ObjectId;
MongoClient.connect(mongoUrl, function(err, database){
    if(err){
        console.log("mongodb error >>"+err);    
    } else {
        db = module.exports = database;
    }});

db.collection('game_users').findOne({_id:ObjectId("123456789")},function(err, data) {});

定义对象:

var db = {__db: undefined}

然后:

exports.db = db
const db = require('./mongo').db.__db