Updating and deleting documents

Now that you've inserted a few documents into your RethinkDB table, you'll probably be wondering how to update or delete these documents using Node.js.

You'll be happy to know that the queries for updating and removing are exactly the same as the ones you learned in Chapter 2, The ReQL Query Language and used in the web interface. Let's go over them very briefly.

RethinkDB provides us with the update command to update the existing documents. This command accepts as input a JSON document with the required changes. As an example, suppose we want to add a gender field to all documents in the fake_data table. We can do so with the following lines of code:

r.table('fake_data').update({gender: "male"}).run(conn, function(err, result) {
    if (err) throw err;
    console.log(result);
});

As you can see, the query syntax is exactly the same as running it from the web interface. The only difference is appending the run command at the end of the query.

Now, let's take look at how to delete the existing documents. Depending on whether you want to delete a specific or all documents, you may need to use the filter command. If you want to delete a specific document, you first filter the dataset using the filter command and then append the delete command at the end of the query. If we want to remove all documents from the table, the following lines do just that:

r.table('fake_data').delete().run(conn, function(err, result) {
    if (err) throw err;
    console.log(result);
});

In the following section, we'll explore one of the most powerful features of RethinkDB: Changefeeds.

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

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