如何让变量保存 mongodb 数据库

How to let a variable hold a mongodb database

本文关键字:mongodb 数据库 保存 变量      更新时间:2023-09-26

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

数据库.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;
};

有没有办法做到这一点,或者我必须在连接功能中做所有事情?我假设它可能与回调函数或其他东西有关。任何帮助都深表感谢。

你的假设是正确的 - 你只能在这个回调中使用db变量

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

在这里你可以用例子进行详细的解释:nodeJs 回调简单的例子