最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Express js,mongodb: “ReferenceError: db is not defined” when calling a function - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question edited May 23, 2017 at 12:33 CommunityBot 11 silver badge asked Dec 21, 2016 at 7:02 Shawn YShawn Y 271 gold badge1 silver badge6 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

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.

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

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?

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

how to get databases list https://stackoverflow./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./docs

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论