Node.js重用MongoDB引用

kal*_*l3v 15 mongodb node.js

我无法理解node.js.

例如,MongoDB访问,这是我所拥有的(mydb.js):

var mongodb = require('mongodb'),
    server = new mongodb.Server('staff.mongohq.com', 10030, {
        auto_reconnect: true
    }),
    db = new mongodb.Db('mydb', server);

function authenticateAndGo(db, handle) {
    db.authenticate('username', 'password', function(err) {
        if (err) {
            console.log(err);
            return;
        }
        console.log('Database user authenticated');

        var collection = new mongodb.Collection(db, 'test');

        handle(collection);
    });
}

function query(handle) {
    db.open(function(err, db) {
        if( err ) {
            console.log(err);
            return;
        }
        console.log('Database connected');

        authenticateAndGo(db, handle);
    });
};
exports.query = query;
Run Code Online (Sandbox Code Playgroud)

所以,如果我想稍后使用它,我会的

var mydb = require('./mydb');
mydb.query(function(collection) {
    collection.find({}, {
        limit: 10
    }).toArray(function(err, docs) {
        console.log(docs);
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,如果我做多个电话,就像这样:

var mydb = require('./mydb');
mydb.query(function(collection) {
    collection.find({}, {
        limit: 10
    }).toArray(function(err, docs) {
        console.log(docs);
    });
});
mydb.query(function(collection) {
    collection.find({}, {
        limit: 10
    }).toArray(function(err, docs) {
        console.log(docs);
    });
});
Run Code Online (Sandbox Code Playgroud)

我得到一个例外:

Error: db object already connecting, open cannot be called multiple times
Run Code Online (Sandbox Code Playgroud)

我认为有一些基本的东西,我不明白这一切,很可能这个问题是愚蠢的......

无论如何,欢迎所有的帮助.

提前致谢.

Poo*_*imi 10

mydb.js:

var mongodb= require('mongodb'),
  server = new mongodb.Server('staff.mongohq.com', 10030, {
    auto_reconnect: true
  }),
  db1 = new mongodb.Db('mydb', server);


// callback: (err, db)
function openDatabase(callback) {
  db1.open(function(err, db) {
    if (err)
      return callback(err);

    console.log('Database connected');

    return callback(null, db);
  });
}

// callback: (err, collection)
function authenticate(db, username, password, callback) {
  db.authenticate(username, password, function(err, result) {
    if (err) {
      return callback (err);
    }
    if (result) {
      var collection = new mongodb.Collection(db, 'test');

      // always, ALWAYS return the error object as the first argument of a callback
      return callback(null, collection);
    } else {
      return callback (new Error('authentication failed'));
    }
  });
}

exports.openDatabase = openDatabase;
exports.authenticate = authenticate;
Run Code Online (Sandbox Code Playgroud)

use.js:

var mydb = require('./mydb');
// open the database once
mydb.openDatabase(function(err, db) {
  if (err) {
    console.log('ERROR CONNECTING TO DATABASE');
    console.log(err);
    process.exit(1);
  }

  // authenticate once after you opened the database. What's the point of 
  // authenticating on-demand (for each query)?
  mydb.authenticate(db, 'usernsame', 'password', function(err, collection) {
    if (err) {
      console.log('ERROR AUTHENTICATING');
      console.log(err);
      process.exit(1);
    }

    // use the returned collection as many times as you like INSIDE THE CALLBACK
    collection.find({}, {limit: 10})
    .toArray(function(err, docs) {
      console.log('\n------ 1 ------');
      console.log(docs);
    });

    collection.find({}, {limit: 10})
    .toArray(function(err, docs) {
      console.log('\n------ 2 ------');
      console.log(docs);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

结果:

成功:

 Database connected
 Database user authenticated

------ 1 ------
[ { _id: 4f86889079a120bf04e48550, asd: 'asd' } ]

------ 2 ------
[ { _id: 4f86889079a120bf04e48550, asd: 'asd' } ]
Run Code Online (Sandbox Code Playgroud)

失败时:

Database connected
{ [MongoError: auth fails] name: 'MongoError', errmsg: 'auth fails', ok: 0 }
Run Code Online (Sandbox Code Playgroud)

[原始答案]:

你打开db多次(每次一次query).您应该只打开一次数据库,并使用db回调中的对象供以后使用.

您多次使用相同的变量名称,这可能会引起一些混淆.

var mongodb = require('mongodb'),
    server = new mongodb.Server('staff.mongohq.com', 10030, {
        auto_reconnect: true
    }),
    db1 = new mongodb.Db('mydb', server);

function authenticateAndGo(db, handle) {
    db.authenticate('username', 'password', function(err) {
        if (err) {
            console.log(err);
            return;
        }
        console.log('Database user authenticated');

        var collection = new mongodb.Collection(db, 'test');

        handle(collection);
    });
}

function query(handle) {
    db1.open(function(err, db2) {
        if( err ) {
            console.log(err);
            return;
        }
        console.log('Database connected');

        authenticateAndGo(db2, handle);
    });
};
exports.query = query;
Run Code Online (Sandbox Code Playgroud)

我已经改变了上面的代码(db1对于原始数据库,db2对于打开的数据库).正如你所看到的,你是db1多次打开,这并不好.提取代码以打开另一个方法并使用它ONCE并使用db2实例进行所有查询/更新/删除/ ...


小智 8

你只能打电话"打开"一次.当打开回调触发时,您可以对它返回的DB对象进行查询.因此,处理此问题的一种方法是将请求排队,直到打开完成.例如MyMongo.js

var mongodb = require('mongodb');

function MyMongo(host, port, dbname) {
    this.host = host;
    this.port = port;
    this.dbname = dbname;

    this.server = new mongodb.Server(
                              'localhost', 
                              9000, 
                              {auto_reconnect: true});
    this.db_connector = new mongodb.Db(this.dbname, this.server);

    var self = this;

    this.db = undefined;
    this.queue = [];

    this.db_connector.open(function(err, db) {
            if( err ) {
                console.log(err);
                return;
        }
        self.db = db;
        for (var i = 0; i < self.queue.length; i++) {
            var collection = new mongodb.Collection(
                                 self.db, self.queue[i].cn);
            self.queue[i].cb(collection);
        }
        self.queue = [];

    });
}
exports.MyMongo = MyMongo;

MyMongo.prototype.query = function(collectionName, callback) {
    if (this.db != undefined) {
        var collection = new mongodb.Collection(this.db, collectionName);
        callback(collection);
        return;
    }
    this.queue.push({ "cn" : collectionName, "cb" : callback});
}
Run Code Online (Sandbox Code Playgroud)

然后使用示例:

var MyMongo = require('./MyMongo.js').MyMongo;

var db = new MyMongo('localhost', 9000, 'db1');
var COL = 'col';

db.query(COL, function(collection) {
    collection.find({}, {
        limit: 10
    }).toArray(function(err, docs) {
        console.log("First:\n", docs);
    });
});


db.query(COL, function(collection) {
    collection.find({}, {
        limit: 10
    }).toArray(function(err, docs) {
        console.log("\nSecond:\n", docs);
    });
});
Run Code Online (Sandbox Code Playgroud)