Express js,mongodb: 调用函数时出现“ReferenceError: db is not defined”

新手上路,请多包涵

代码是这样设置的:

 var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient;

function getData(){
  db.collection("collection_name").find({}).toArray(function (err, docs) {
      if (err) throw err;
      //doing stuff here
      }

      var dataset = [
          {//doing more stuff here
          }
      ];
  });
}

router.get("/renderChart", function(req, res) {
    mongo.connect(url_monitor, function (err, db) {
        assert.equal(null, err);
        getData(res);
    });
});

当我运行代码并尝试在运行时访问 /renderChart 时,我收到“ReferenceError: db is not defined”。我遇到了类似的情况,并认为这可能是由于异步调用 mongodb.connect() 而引起的类似问题,但我无法使其工作:

Express js,mongodb:在post函数外提到db时出现“ReferenceError: db is not defined”

原文由 Shawn Y 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.5k
2 个回答

这里的问题是你没有将 db 传递给函数,所以它是 undefined

一个解法:

 function getData(db, res){
  db.collection("collection_name").find({}).toArray(function (err, docs) {
      if (err) throw err;
      //doing stuff here
      }

      var dataset = [
          {//doing more stuff here
          }
      ];
  });
}

router.get("/renderChart", function(req, res) {
    mongo.connect(url_monitor, function (err, db) {
        assert.equal(null, err);
        getData(db, res);
    });
});

您可能也需要在某个时候传递 req ,或者进行特定的数据库查询。您可能希望使用 promises 或 async/await 来更好地处理所有异步调用。

原文由 Denys Séguret 发布,翻译遵循 CC BY-SA 3.0 许可协议

你没有告诉代码,你想使用哪个数据库。

如何获取数据库列表 https://stackoverflow.com/a/71895254/17576982

here is the sample code to find the movie with name 'Back to the Future' in database sample_mflix > collection movies :

 const { MongoClient } = require("mongodb");

// Replace the uri string with your MongoDB deployment's connection string.
const uri =
  "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";

const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();

    const database = client.db('sample_mflix');
    const movies = database.collection('movies');

    // Query for a movie that has the title 'Back to the Future'
    const query = { title: 'Back to the Future' };
    const movie = await movies.findOne(query);

    console.log(movie);
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

要获取数据库列表,请将 await client.db().admin().listDatabases() 放在 fun 函数上。例如

async function run() {
  try {
    await client.connect();
    var databasesList = await client.db().admin().listDatabases();
    console.log("Databases:");
    databasesList.databases.forEach(db => console.log(` - ${db.name}`));

从官方文档了解更多 MongoDB:https: //www.mongodb.com/docs

原文由 aakash4dev 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题