Node.js重用MongoDB参考 [英] Node.js reuse MongoDB reference

查看:127
本文介绍了Node.js重用MongoDB参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解node.js.

I am having trouble understanding node.js.

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

Example, MongoDB access, here's what I've got (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;

所以,如果我以后要使用它,我会

So, if I want to use it later, I would

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

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

But, If I do multiple calls, like so:

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

我得到一个例外:

Error: db object already connecting, open cannot be called multiple times

我认为对这一切我确实不了解,并且这个问题很可能是愚蠢的...

I think that there is really something fundamental that I do not understand about all this and it is probable that this question is stupid ...

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

Anyway, all help is welcome.

谢谢.

推荐答案

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;

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

结果:

成功:

 Database connected
 Database user authenticated

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

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

失败时:

Database connected
{ [MongoError: auth fails] name: 'MongoError', errmsg: 'auth fails', ok: 0 }


[原始答案]:

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

You're opening the db multiple times (once in each query). You should open the database just once, and use the db object in the callback for later use.

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

You're using the same variable name multiple times, and that might've caused some confusion.

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;

我对上面的代码做了一些更改(原始数据库为db1,打开 数据库为db2).如您所见,您多次打开db1,这不好.提取要打开的代码以另一种方法使用,一次使用它,并对所有查询/更新/删除/...使用db2实例

I've changed the above code a little (db1 for the original db, db2 for the opened db). As you can see, you're opening db1 multiple times, which is not good. extract the code for opening into another method and use it ONCE and use the db2 instance for all your queries/updates/removes/...

这篇关于Node.js重用MongoDB参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆