Mongoose Connection

后端 未结 5 752
长情又很酷
长情又很酷 2020-12-09 09:31

I read the quick start from the Mongoose website and I almost copy the code, but I cannot connect the MongoDB using Node.js.

var mongoose = require(\'mongoos         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 10:10

    Mongoose's default connection logic is deprecated as of 4.11.0. It is recommended to use the new connection logic:

    • useMongoClient option
    • native promise library

    Here is the example from npm module: 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;
    }
    

提交回复
热议问题