繁体   English   中英

如何让变量保存mongodb数据库

[英]How to let a variable hold a mongodb database

所以基本上,我正在尝试设置一个可以直接从其查询mongodb的变量。 我的代码如下所示:

db.js

var mongo = require('mongodb').MongoClient;
var DB = null;
var dbURL = 'mongodb://localhost:27017';
exports.connect = function(cb) {

    console.log('meep'); //tracing code

    mongo.connect(dbURL, function(err, db){
        console.log('lmao'); //tracing
        if (err) throw Error('Something has went wrong');
        else { DB=db; console.log(DB); cb();}

    });
    console.log(DB); //returns null
};
//if some other file requires this file as mydbjs for example,
//I want to be able to do mydbjs.db().collection('epik').find(); 
exports.db = function() {
    if (DB === null) throw Error('DB Object has not yet been initialized');
    return DB;
};

有没有办法做到这一点,还是我必须在connect函数中做所有事情? 我假设它可能与回调函数有关。 任何帮助深表感谢。

您的假设是正确的-您只能在此回调中使用db变量

function(err, db){
    console.log('lmao'); //tracing
    if (err) throw Error('Something has went wrong');
    else { DB=db; console.log(DB); cb();}
});

在这里,您可以使用示例进行详细说明: nodeJs回调简单示例

暂无
暂无

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

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