【问题标题】:Mongoose Connection猫鼬连接
【发布时间】:2021-11-26 13:36:14
【问题描述】:

我阅读了the Mongoose website 的快速入门,几乎复制了代码,但我无法使用 Node.js 连接 MongoDB。

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

exports.test = function(req, res) {
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));
  console.log("h1");
  db.once('open', function callback () {
    console.log("h");
  });
  res.render('test');
};

这是我的代码。控制台只打印h1,而不是h。我哪里错了?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    当你调用mongoose.connect时,它会与数据库建立连接。

    但是,您在更晚的时间点(正在处理请求时)附加 open 的事件侦听器,这意味着连接可能已经处于活动状态并且已经调用了 open 事件(您只是还没听)。

    您应该重新排列您的代码,以便事件处理程序尽可能接近(及时)连接调用:

    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/test');
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function callback () {
      console.log("h");
    });
    
    exports.test = function(req,res) {
      res.render('test');
    };
    

    【讨论】:

    • 它应该首先监听事件,然后建立连接。顺序相反
    • @xwa130 异步多少?
    【解决方案2】:

    最安全的方法是“监听连接事件”。这样您就不必关心数据库需要多长时间才能为您提供连接。

    一旦完成 - 您应该启动服务器。此外.. config.MONGOOSE 在您的应用程序中公开,因此您只有一个数据库连接。

    如果你想使用 mongoose 的连接,只需在你的模块中 require config,然后调用 config.Mongoose。希望这对某人有所帮助!

    这是代码。

    var mongoURI;
    
    mongoose.connection.on("open", function(ref) {
      console.log("Connected to mongo server.");
      return start_up();
    });
    
    mongoose.connection.on("error", function(err) {
      console.log("Could not connect to mongo server!");
      return console.log(err);
    });
    
    mongoURI = "mongodb://localhost/dbanme";
    
    config.MONGOOSE = mongoose.connect(mongoURI);
    

    【讨论】:

    • 这段代码比接受的答案更可靠,而接受的答案解释得更清楚。
    • 这很有帮助。我确定问题出在我的连接字符串上,因为我第一次使用新数据库时总是遇到问题。此代码确认了我需要的问题。
    【解决方案3】:

    使用单例模式的猫鼬连接

    Mongoose 连接文件 - db.js

    //Import the mongoose module
    const mongoose = require('mongoose');
    
    class Database { // Singleton
      connection = mongoose.connection;
      
      constructor() {
        try {
          this.connection
          .on('open', console.info.bind(console, 'Database connection: open'))
          .on('close', console.info.bind(console, 'Database connection: close'))
          .on('disconnected', console.info.bind(console, 'Database connection: disconnecting'))
          .on('disconnected', console.info.bind(console, 'Database connection: disconnected'))
          .on('reconnected', console.info.bind(console, 'Database connection: reconnected'))
          .on('fullsetup', console.info.bind(console, 'Database connection: fullsetup'))
          .on('all', console.info.bind(console, 'Database connection: all'))
          .on('error', console.error.bind(console, 'MongoDB connection: error:'));
        } catch (error) {
          console.error(error);
        }
      }
    
      async connect(username, password, dbname) {
        try {
          await mongoose.connect(
            `mongodb+srv://${username}:${password}@cluster0.2a7nn.mongodb.net/${dbname}?retryWrites=true&w=majority`,
            {
              useNewUrlParser: true,
              useUnifiedTopology: true
            }
          );
        } catch (error) {
          console.error(error);
        }
      }
    
      async close() {
        try {
          await this.connection.close();
        } catch (error) {
          console.error(error);
        }
      }
    }
    
    module.exports = new Database();
    

    从 app.js 调用连接

    const express = require("express"); // Express Server Framework
    
    const Database = require("./utils/db");
    
    const app = express();
    
    Database.connect("username", "password", "dbname");
    
    module.exports = app;
    

    【讨论】:

      【解决方案4】:

      我有同样的错误弹出。然后我发现我没有运行和监听连接的 mongod。为此,您只需打开另一个命令提示符 (cmd) 并运行 mongod

      【讨论】:

        【解决方案5】:

        Mongoose 的默认连接逻辑自 4.11.0 起已弃用。推荐使用新的连接逻辑:

        • 使用MongoClient 选项
        • 原生承诺库

        这是来自 npm 模块的示例:mongoose-connect-db

        // Connection options
        const defaultOptions = {
          // Use native promises (in driver)
          promiseLibrary: global.Promise,
          useMongoClient: true,
          // Write concern (Journal Acknowledged)
          w: 1,
          j: true
        };
        
        function connect (mongoose, dbURI, options = {}) {
          // Merge options with defaults
          const driverOptions = Object.assign(defaultOptions, options);
        
          // Use Promise from options (mongoose)
          mongoose.Promise = driverOptions.promiseLibrary;
        
          // Connect
          mongoose.connect(dbURI, driverOptions);
        
          // If the Node process ends, close the Mongoose connection
          process.on('SIGINT', () => {
            mongoose.connection.close(() => {
              process.exit(0);
            });
          });
        
          return mongoose.connection;
        }
        

        【讨论】:

        • 感谢您的建议。添加示例
        【解决方案6】:

        我建立连接的简单方法:

        const mongoose = require('mongoose')

        mongoose.connect(<connection string>);
        mongoose.Promise = global.Promise;
        mongoose.connection.on("error", error => {
            console.log('Problem connection to the database'+error);
        });
        

        【讨论】:

          猜你喜欢
          • 2016-04-13
          • 1970-01-01
          • 1970-01-01
          • 2015-12-30
          • 1970-01-01
          • 1970-01-01
          • 2021-10-25
          • 2020-06-10
          • 2015-08-16
          相关资源
          最近更新 更多