Node.js reuse MongoDB reference

前端 未结 3 1753
萌比男神i
萌比男神i 2021-01-31 11:35

I am having trouble understanding node.js.

Example, MongoDB access, here\'s what I\'ve got (mydb.js):

var mongodb = require(\'mongodb\'),
    server = ne         


        
3条回答
  •  孤独总比滥情好
    2021-01-31 12:08

    You can only call "open" once. When the open callback fires, you can then do your queries on the DB object it returns. So one way to handle this is to queue up the requests until the open completes. e.g 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});
    }
    

    and then a sample use:

    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);
        });
    });
    

提交回复
热议问题