代码之家  ›  专栏  ›  技术社区  ›  jboxxx

mongoose.connect(connectionsring)如何工作?

  •  1
  • jboxxx  · 技术社区  · 7 年前

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

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

    更具体地说,通过返回的连接对象将我的所有调用定向到数据库 conn 不是图书馆 CXI甲骨文 本身。

    在一个 express 应用程序,使用MongoDB node.js mongoose ,我们可能在做如下的事情:

    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.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 理解这一点,但对返回语句感到困惑。承诺完成后,它返回一个箭头函数, _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(...) ?或者发送一些资源以便我能看到一个简单的例子?谢谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   GaneshMani    7 年前

    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
    
    推荐文章