如果rethinkdb中需要,请创建数据库

Nan*_*ano 2 javascript node.js rethinkdb

这是我与rethinkdb的第一次互动,它看起来不错,但我遇到了一些问题......

这个想法很简单:如果尚未创建数据库,则创建数据库.

代码很简单,或者很好,代码的概念:

module.exports = function(r, config) {
  var connection = null;

  r.connect(config.rdb, function(err, conn) {
    if (err) throw err
      connection = conn;
  });

  r.dbList()
    .contains('semestres')
    .do(function(dbExists) {
      return r.branch(
        dbExists,
        { created: 0 },
        r.dbCreate('semestres')
      );
    })
    .run(connection, function(err) {
      if (err) throw err;
    });
};
Run Code Online (Sandbox Code Playgroud)

因此,这只是创建一个连接并指定与变量的连接,然后检查数据库是否存在"semestres",如果它存在,它什么都不做,否则,创建它.

但不是,我在运行服务器时遇到此错误:

Unhandled rejection RqlDriverError: First argument to `run` must be an open connection.
    at new RqlDriverError (/home/nano/Dev/semestres/node_modules/rethinkdb/errors.js:14:13)
    at FunCall.TermBase.run (/home/nano/Dev/semestres/node_modules/rethinkdb/ast.js:129:29)
    at module.exports (/home/nano/Dev/semestres/config/database.js:20:6)
    at Object.<anonymous> (/home/nano/Dev/semestres/server.js:10:29)
    at Module._compile (module.js:428:26)
    at Object.Module._extensions..js (module.js:446:10)
    at Module.load (module.js:353:32)
    at Function.Module._load (module.js:308:12)
    at Function.Module.runMain (module.js:469:10)
    at startup (node.js:124:18)
    at node.js:882:3
Run Code Online (Sandbox Code Playgroud)

那么,我如何在rethinkdb中进行这种类型的操作?

Jor*_*lva 7

因为这是JavaScript并且代码是异步的,所以您的dbList查询无法访问您的connection变量.您需要将dbList代码放在 connect回调中.

module.exports = function(r, config) {
  var connection = null;

  r.connect(config.rdb, function(err, conn) {
    if (err) throw err
      connection = conn;
      r.dbList()
        .contains('semestres')
        .do(function(dbExists) {
          return r.branch(
            dbExists,
            { created: 0 },
            r.dbCreate('semestres')
          );
        })
        .run(connection, function(err) {
          if (err) throw err;
        });
    };
  });
Run Code Online (Sandbox Code Playgroud)

这与RethinkDB本身无关,但与JavaScript的作用方式有关.