Search code examples
rethinkdbnsq

not insert data to rethinkdb


i am trying to create NSQ topic and insert data at rethinkdb but i am unable to insert the data into rethinkdb. Can anyone help me.

**var nsq = require('nsqjs');
var r = require('rethinkdb');
var nsqdd = (process.env.NSQD_RETH || "localhost:4161").split(",");
var connection = null;
r.connect( {host: 'localhost', port: 28015, db:'test', authKey:''}, function(err, conn) {
    if (err) throw err;
    connection = conn;
})
var eventreader;
eventreader = new nsq.Reader('ev_topic', 'ev_channel', {
    lookupdHTTPAddresses: nsqdd
});
eventreader.connect();
eventreader.on('message', function (msg) {
    r.table('rethinkdb_test').insert(msg.json()).run(conn);
    console.log('Received message [%s]: %s', msg.id, msg.body.toString());
    msg.finish();
});**

Solution

  • It seems like your second query (the insert) does not have access to the conn variable. For this to work, you'd need to put the event reader code inside the callback for your connect function.

    var nsq = require('nsqjs');
    var r = require('rethinkdb');
    var nsqdd = (process.env.NSQD_RETH || "localhost:4161").split(",");
    var connection = null;
    r.connect( {host: 'localhost', port: 28015, db:'test', authKey:''}, function(err, conn) {
        if (err) throw err;
        connection = conn;
        // Event Reader functionality inside connect callback
        var eventreader;
        eventreader = new nsq.Reader('ev_topic', 'ev_channel', {
            lookupdHTTPAddresses: nsqdd
        });
        eventreader.connect();
        eventreader.on('message', function (msg) {
            // Now we have access to the connection
            r.table('rethinkdb_test').insert(msg.json()).run(conn);
            console.log('Received message [%s]: %s', msg.id, msg.body.toString());
            msg.finish();
        });
    });