mongodb:无法定义变量

时间:2017-11-06 22:28:56

标签: javascript node.js mongodb

[使用node.js和mongodb]

我在adminDb变量上收到错误消息如下:adminDb is not defined;但是,我在JS中将它定义为db.admin()以用于Mongodb。这是基本代码,但由于某种原因,它不能在我的服务器/数据库上运行。此外,我正在使用8个数据库,每个数据库都有一些集合。

server.js代码:

    const mongoClient = require('mongodb').MongoClient;
    const mongoDBurl = process.env.mongo_url || "mongodb://10.119.224.149:27017/logServer";
    var adminDb;

    logServer.post('/test', (req,res) => { //Postman calls here
        console.log('starting test');
        res.status(200).send('hello, I am Log test');

        adminDb.listDatabases(function(err, dbs) { //ERROR HERE **
        test.equal(null, err);
        test.ok(dbs.databases.length > 0);

        db.close();
      });
    });

mongoClient.connect(mongoDBurl, function(error, db){ //to connect to mongodb 
    if (error) {
        console.log("Failed to connect to db. Restart sever.");
        return;
    } 
    console.log("Connected to mongodb :" + mongoDBurl);
     adminDb = db.admin();
});

错误消息:

 ReferenceError: adminDb is not defined
     at /app/server.js:469:11
     at connectCallback (/app/node_modules/mongodb/lib/mongo_client.js:507:5)
    at /app/node_modules/mongodb/lib/mongo_client.js:426:11
     at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

0 个答案:

没有答案