Nano Nano - 2 months ago 22
Javascript Question

Create a database if is needed in rethinkdb

This is my very first interaction with rethinkdb, it looks pretty good but i'm having some problems...

The idea is simple: create a database if is not created yet.

The code is simple, or well, the idea of code:

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


So, this just creates a connection and asign the connection to the variable, then checks if a database "semestres" exists, if it exists, it does nothing, else, create it.

But not, i get this error when run the server:

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


So, how i can make this type of operations in rethinkdb?

Answer

Because this is JavaScript and the code is asynchronous, your dbList query does not have access to your connection variable. You need to put your dbList code inside the connect callback.

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

This has nothing to do with RethinkDB itself, but with the way scoping works in JavaScript.