'Express js,mongodb: “ReferenceError: db is not defined” when calling a function

The code is set up this way:

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);
    });
});

When I run the code and trying to get to /renderChart when running, I get the "ReferenceError: db is not defined". I came across a similar case, and think it may be a similar problem caused because mongodb.connect() is called asynchronously, but I couldn't get it to work:

Express js,mongodb: "ReferenceError: db is not defined" when db is mentioned outside post function



Solution 1:[1]

The problem here is you don't pass the db to the function, so it's undefined.

A solution:

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);
    });
});

You'll probably need to pass the req at some point too, or make specific db queries. And you'll probably want to use promises or async/await to better deal with all asynchronous calls.

Solution 2:[2]

Its Simple Javascript. You are using a variable db in your file, which is not defined, so it will throw an error.

You need to do something like this .

var findDocuments = function(db, callback) {
  // Get the documents collection 
  var collection = db.collection('documents');
  // Find some documents 
  collection.find({}).toArray(function(err, docs) {
    assert.equal(err, null);
    assert.equal(2, docs.length);
    console.log("Found the following records");
    console.dir(docs);
    callback(docs);
  });
}

Solution 3:[3]

I have the same problem before, instead of passing db to routing function, My solution is to make db variable global like

var mongojs = require('mongojs')
global.db = mongojs(<mongodb url>);

then db variable can be used in any part of your code

If you're using express, put that in your app.js file and you will never have to worry about db variable anyore.

PS: some people think that using global is not a good practices, but I argue that since global is a node.js features and especially since it works, why not node.js global variables?

Solution 4:[4]

You don't have tell the codes, that which database you want to use.

how to get databases list 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);

to get list of database, put await client.db().admin().listDatabases() on fun function. e.g.

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}`));

learn MongoDB more from official docs: https://www.mongodb.com/docs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Denys Séguret
Solution 2 Parth Ghiya
Solution 3 Community
Solution 4 aakash4dev