【问题标题】:How does mongoose.connect(connectionSring) work?mongoose.connect(connectionSring) 是如何工作的?
【发布时间】:2019-06-27 13:07:26
【问题描述】:

当我连接到数据库并在没有 ORM 的情况下执行 sql 时,我来自 python 背景。用python库cx_Oracle说,像这样:

>>> conn = cx_Oracle.connect(connectionString)
>>> curs = conn.cursor()
>>> _ = curs.execute(...)

更具体地说,通过返回的连接对象 conn,而不是库 cx_Oracle 本身,将我所有的调用定向到数据库。

express 应用程序中,使用带有node.jsmongoose 的mongodb,我们可能会执行以下操作:

require('./models/user'); // Defines new Schema in mongoose named 'users'
require('./services/passport');  // receives data from OAuth flow
// and writes new authenticated users to MongoDB database

mongoose.connect(keys.mongoURI, {useNewUrlParser: true});

const app = express();
require('./routes/authRoutes')(app);  // handle OAuth routes and pass to passport authentication

// server runs and listens to routes etc

似乎导入的库 mongoose 本身正在设置来自以下位置的新属性:

mongoose.connect(keys.mongoURI, {useNewUrlParser: true});

因为随后在./services/passport.js 中创建新用户的调用对我们的连接没有明显的参考。

const User = mongoose.model('users');

// within an OAuth callback
new User({ id: response.data.id })
  .save()
  .then(...)

我查看了Mongoose.prototype.connect 的来源以了解这一点,但对返回语句感到困惑。 Promise 完成后,它返回一个带有 _mongoose 的箭头函数,我们的原型实例 Mongoose 本身带有一个新连接,但我们的应用程序中没有返回任何内容。

Mongoose.prototype.connect = function() {
  const _mongoose = this instanceof Mongoose ? this : mongoose;
  const conn = _mongoose.connection;
  return conn.openUri(arguments[0], arguments[1], arguments[2]).then(() => _mongoose);
};

当我们调用mongoose.connect(...) 时,有人可以解释一下我们导入的mongoose 库发生了什么吗?或者也许发送一些资源,以便我可以看到一个简单的例子?谢谢。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    Mongoose 会尝试在内部连接 ​​MongoClient 并返回 mongoose 的实例。

    const promise = new Promise((resolve, reject) => {
        const client = new mongodb.MongoClient(uri, options);
        _this.client = client;
        client.connect(function(error) {
          if (error) {
            _this.readyState = STATES.disconnected;
            return reject(error);
          }
    
          const db = dbName != null ? client.db(dbName) : client.db();
          _this.db = db;
    
    }
    

    这是“conn.openUri”函数的内部进程,mongoose会执行该函数。也可以不使用mongoose直接连接mongoClient。

    https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html
    

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 1970-01-01
      • 2015-06-12
      • 2021-03-08
      • 2021-01-26
      • 2021-03-17
      • 2017-07-24
      • 2016-11-13
      • 2017-10-11
      相关资源
      最近更新 更多