Inserting documents

In this example, we're going to look at how to insert some data into our newly created table. As you may remember from Chapter 2, The ReQL Query Language you can add data to a table using the insert command. Adding data from a RethinkDB script follows exactly the same syntax.

As an example, a query that inserts the name of a person into the database looks as follows:

r.table("posts").insert({ name: "Matt" }).run(conn, callback);

It's now time to write our first full-fledged Node.js script. We're going to write a script that inserts some random data generated by a Node.js module. In particular, we're going to insert data about people: a name and an e-mail address.

To generate this sample data, we are going to use a module called faker. The first step is to install this module using the NPM package manager. You can do so by running the following command from a terminal window:

sudo npm install faker

We are now going to write a script that generates 100 random names and e-mail addresses and inserts them into the fake_data table.

First, we import the RethinkDB and faker modules:

var r = require('rethinkdb');
var faker = require('faker');

Once our modules have been loaded, we need to connect to the database. We can do so with the following code:

var connection = null;
r.connect({host: 'localhost', port: 28015}, function(err, conn) {
    if (err) throw err;
    connection = conn;
});

Finally, we need to write the function that generates the random data and inserts it into the database:

function insertData() {
    var itemsToInsert = 100;
    for(var i=0;i<itemsToInsert;i++) {
        var randomName = faker.name.findName();
        var randomEmail = faker.internet.email();
        r.table("fake_data").insert({ name: randomName, email:randomEmail }).run(connection, function(err, data) {
            if (err) throw err;
        });
    }
}

It's a bit complicated to see what's actually going on, so let's go over this function line by line:

  • First, we define a variable that contains the number of items we want to add to the database table and use this variable to initialize the for loop.
  • Inside the loop, we use the Faker module to generate our random data. In particular, we use the library's findName function that generates a random full name and the e-mail function that generates a random email address. We assign the generated data to two variables.
  • Finally, we call the insert command to pass our random data as arguments.

Now, this is a much more interesting script! Before running the script, however, we may want to print a message when all the data has been inserted into the database table. To do this, we pass a callback function as an argument to the insertData function and call this callback when all the insert queries are completed.

You can view the complete source code by opening the example1.js file that accompanies this book.

We're now ready to run our JavaScript script:

node example1.js

If there are no errors, you will receive the following confirmation message:

Inserted 100 documents!

Congratulations! You've just written your first Node.js script that interacts with RethinkDB.

We can check that the data has effectively been written to the database by running a query on our table, appending the count command at the end of the query. Let's try running this from the Node.js CLI.

First, run the node command, and then type the following code in the command line:

$ node
>r = require('rethinkdb');
>r.connect({host: 'localhost', port: 28015}, function(err, conn) {
if(err) throw err;
r.db('test').table('fake_data').count().run(conn, function(err, res) {
if(err) throw err;
console.log(res);
});
});

If all the documents have been inserted correctly, the output will be 100.

In this section, you learned how to insert data into the database using Node.js. In the following section, we'll take look at how to read data from the database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.255.249