【问题标题】:Connecting Mongodb databse to node.js server将 Mongodb 数据库连接到 node.js 服务器
【发布时间】:2022-02-08 15:24:51
【问题描述】:

我一直在尝试使用 node.js 和 express 制作一个 web 应用程序,并决定使用 mongodb。 我正在使用 mongodb node.js 驱动程序版本:4.3.1 我已经尝试了所有可能的方法来连接 node.js 服务器和我的 mongodb atlas 数据库。

我的数据库也使用我的 db.js 文件中的以下代码连接:

const app = require('./app');

const MongoClient = require('mongodb').MongoClient

const Url = 'mongodb+srv://todoAppUser:<myOriginalPasswordHere>@cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority';

MongoClient.connect(Url, function (err, client) {
  if (err) throw err;

  var db = client.db('myDatabase');

  db.collection('products').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
});

上面的代码工作正常,并且也给出了输出。 但我想使用需要导出连接的 MVC(模型-视图-控制器)框架。

我在上面的代码中做了如下改动:

MongoClient.connect(Url, function (err, client) {
  if (err) throw err;

  var db = client.db('myDatabase');

  db.collection('products').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
  module.exports = db
    client.close();
  });
});

更改后,当我尝试从我的任何其他文件访问我的连接 (const productCollection = require('./db').collection("product");) 时,它给了我以下错误:

const productCollection = require('./db').collection("product");
                                          ^

TypeError: require(...).collection is not a function
    at Object.<anonymous> (D:\Kush- Complete Data\exp-projects\nodeApp\productController.js:1:43)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (D:\Kush- Complete Data\exp-projects\nodeApp\router.js:3:27)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
[nodemon] app crashed - waiting for file changes before starting...

请任何人指导我并指出可能的出路。

谢谢, 库什

【问题讨论】:

    标签: javascript node.js mongodb express connection


    【解决方案1】:

    这是行不通的,因为模块是同步评估的。您的回调被异步调用,但此时您的模块已被评估。意味着module.exports 没有效果并且require('./db').collection() 没有定义。详情请见Node.js Modules

    要解决您的问题,请处理存储在模块内部变量中的连接并导出 getter 而不是连接变量本身。

    // db.js
    let client;
    let db;
    
    function connectDB(url, dbName) {
        client = new MongoClient(url);
    
        return new Promise(function(resolve, reject) {
            client.connect(function(err) {
                if(err) return reject(err);
    
                db = client.db(dbName);
                return resolve(db);
            });
        });
    }
    
    function getCurrentDB() {
        return db;
    }
    
    module.exports.connectDB = connectDB;
    module.exports.getCurrentDB = getCurrentDB;
    

    然后在其他文件中重用您打开的连接,如下所示:

    // other.js
    const db = require("./db.js");
    
    db.getCurrentDB().collection("product");
    

    当然,getCurrentDB() 只能在事先通过connectDB() 建立连接的情况下返回数据库连接。所以你必须等待Promise的解析。

    【讨论】:

      【解决方案2】:

      [已解决] 我发现,在较新版本的 mongodb 中,它们基本上改变了将节点服务器连接到数据库的方式。 为了建立一个可重用的连接(以便我们可以从任何其他文件访问连接的数据库),我在我的db.js 文件中创建了一个异步函数,在该文件中建立了连接,然后将其导出。在文件的末尾,我调用了该函数。 代码如下:

       const {MongoClient} = require('mongodb')
          
          
          const client = new MongoClient('mongodb+srv://todoAppUser:<password>@cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority')
          
          async function start(){
            await client.connect()
            console.log("Connected")
            module.exports = client.db()
            const app = require('./app')
            app.listen(3000)
          }
          
            start()
      

      从另一个文件调用它时:

      const productCollection = require('./db').collection("product");
      

      这段代码没有给我任何错误,并且工作得很好。 借助上述代码,可以在遵循 MVC(Model-View-Controller)框架的同时方便地使用它。

      【讨论】:

        猜你喜欢
        • 2011-08-12
        • 2016-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-20
        • 1970-01-01
        • 2019-05-24
        相关资源
        最近更新 更多