node.jsrethinkdb

Nodejs - rethinkdb Unhandled rejection ReqlDriverError: First argument to `run` must be an open connection


Run simple code as per official document, but getting error

const r = require('rethinkdb');
    var connection = null;
    r.connect( {host: 'localhost', port: 28015}, function(err, conn) {
        if (err) throw err;
        connection = conn;
    })
    
    // r.dbCreate("blog").run(connection, function(err, result) {
    //   if (err) throw err;
    //   console.log(result);
    // });

    r.db('test').tableCreate('authors').run(connection, function(err, result) {
      if (err) throw err;
        console.log(JSON.stringify(result, null, 2));
    })

Unhandled rejection ReqlDriverError: First argument to run must be an open connection. at ReqlDriverError.ReqlError [as constructor] (/Users/tejastank/source/electronjs/website-scanner/node_modules/rethinkdb/errors.js:23:13) at new ReqlDriverError (/Users/tejastank/source/electronjs/website-scanner/node_modules/rethinkdb/errors.js:68:50) at Function.TermBase.run (/Users/tejastank/source/electronjs/website-scanner/node_modules/rethinkdb/ast.js:133:29) at HTMLButtonElement. (file:///Users/tejastank/source/electronjs/website-scanner/index.js:59:41) (node:45504) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.


Solution

  • connection is populated in the .connect() callback, it's not guaranteed to be available exactly after the call. You need to work inside callbacks:

    const r = require('rethinkdb');
    r.connect( {host: 'localhost', port: 28015}, function(err, conn) {
        if (err) throw err;
    
        r.db('test').tableCreate('authors').run(conn, function(err, result) {
            if (err) throw err;
            console.log(JSON.stringify(result, null, 2));
        });
    });
    

    or by using promises:

    const r = require('rethinkdb');
    r.connect({host: 'localhost', port: 28015})
        .then(function(conn) {
            return r.db('test').tableCreate('authors').run(conn);
        })
        .then(function(result) {
            console.log(JSON.stringify(result, null, 2));
        });