title | summary | toc | |
---|---|---|---|
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}}
Make sure you have already installed CockroachDB.
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 %}
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)
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: