Parakoopa
Parakoopa

Reputation: 525

RethinkDB - Run query one after another

I am having trouble running multiple queries inside a single connection with RethinkDB. I have tried the r.do as seen in this question, however no success. I have also tried working with the conditional update queries. What I am looking to do is:

  1. Open the connection.
  2. Query to see if my field is there and if it is, perform some tasks.
  3. Query to see if a counts field is there, subtract it by one.

What would be the best way to go about this? It seems I might be missing something?

r.connect(config.rethinkdb, function(err, conn) {
    if (err) {
        throw err;
    }
    else {
        console.log('Connected.');
        app.set('rethinkdb.conn', conn);
    }
            r.table('upcs').filter({AcceptedUPC:data}).run(conn, (err, cursor) => {
                if (err) throw err;
                console.log(data);
                cursor.toArray((err,resu) => {
                    if (err) throw err;
                    //make a csv with some information
                })
            })       

And in the same connection run

r.table('upcs').filter({AcceptedUPC:data}).filter(r.row.hasFields("UPCCount")).update({UPCCount: r.row("UPCCount").sub(1)}).run(conn, (err,cursor) => {
                        if (err) throw err;
                    });

Running this in NodeJS

Upvotes: 1

Views: 142

Answers (1)

Vladyslav Kochetkov
Vladyslav Kochetkov

Reputation: 147

I'm going to assume you are using this library for node.

You can that they actually allow you to do either callbacks or promises. I would recommend promises to avoid brackets of hell.

For promises you can use the bluebird library to make life easy.

You can do it by doing the following.

r.connect(config.rethinkdb).then(() => {
  console.log("Connected");
  app.set("rethinkdb.conn", conn);
  return r.table('upcs').filter({AcceptedUPC:data}).run(conn);
}).then((cursor) => {
   console.log(data); //maybe this should be cursor but I don't use rethinkDB
   return cursor.toArray();
}).then((resu) => {
   //make a csv with some information
}).catch((err) => {
   throw err;
});

Upvotes: 1

Related Questions