Skip to content

Latest commit

 

History

History
94 lines (67 loc) · 3.27 KB

build-a-nodejs-app-with-cockroachdb-sequelize.md

File metadata and controls

94 lines (67 loc) · 3.27 KB
title summary toc twitter
Build a Node.js App with CockroachDB
Learn how to use CockroachDB from a simple Node.js application with the Sequelize ORM.
false
true

This tutorial shows you how build a simple Node.js application with CockroachDB using a PostgreSQL-compatible driver or ORM. We've tested and can recommend the Node.js pg driver and the Sequelize ORM, so those are featured here.

{{site.data.alerts.callout_success}}For a more realistic use of Sequelize with CockroachDB, see our examples-orms repository.{{site.data.alerts.end}}

Before You Begin

Make sure you have already installed CockroachDB.

Step 1. Install the Sequelize ORM

To install Sequelize, as well as a CockroachDB Node.js package that accounts for some minor differences between CockroachDB and PostgreSQL, run the following command:

$ npm install sequelize sequelize-cockroachdb

{% include app/common-steps.md %}

Step 5. Run the Node.js code

The following code uses the Sequelize ORM to map Node.js-specific objects to SQL operations. Specifically, Account.sync({force: true}) creates an accounts table based on the Account model (or drops and recreates the table if it already exists), Account.bulkCreate([...]) inserts rows into the table, and Account.findAll() selects from the table so that balances can be printed.

Copy the code or download it directly.

{% include app/sequelize-basic-sample.js %}

Then run the code:

$ node sequelize-basic-sample.js

The output should be:

1 1000
2 250

To verify that the table and rows were created successfully, you can again use the built-in SQL client:

$ cockroach sql --insecure -e 'SHOW TABLES' --database=bank
+----------+
|  Table   |
+----------+
| accounts |
+----------+
(1 row)
$ cockroach sql --insecure -e 'SELECT id, balance FROM accounts' --database=bank
+----+---------+
| id | balance |
+----+---------+
|  1 |    1000 |
|  2 |     250 |
+----+---------+
(2 rows)

What's Next?

Read more about using the Sequelize ORM, or check out a more realistic implementation of Sequelize with CockroachDB in our examples-orms repository.

You might also be interested in using a local cluster to explore the following core CockroachDB features: