Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8829

Bot開発(Node.js)のDBアクセスライブラリは knex がオススメ!

$
0
0

Bot開発でNode.jsを使うことが多く、DBアクセスがある要件で pgなどで素のクエリを書いていて辛いなーと感じている時に、 knexに出会ったので紹介します。

公式ドキュメント http://knexjs.org/
GitHub https://github.com/knex/knex

使い方

インストール

$npm install--save knex pg

knex初期設定

$knex init

すると、以下のファイルが自動生成されます。

knexfile.js
// Update with your config settings.module.exports={development:{client:'postgresql',connection:{database:'linebot-dev',user:'zyyx-kubo',password:''},pool:{min:2,max:10},migrations:{directory:'./db/migrations',tableName:'knex_migrations'}},staging:{client:'postgresql',connection:{database:'my_db',user:'username',password:'password'},pool:{min:2,max:10},migrations:{directory:'./db/migrations',tableName:'knex_migrations'}},production:{client:'postgresql',connection:{database:'my_db',user:'username',password:'password'},pool:{min:2,max:10},migrations:{directory:'./db/migrations',tableName:'knex_migrations'}}};

マイグレーションファイルの作成

$knex migrate:make create_user
Using environment: development
Created Migration: ./db/migrations/20190214205707_create_user.js

マイグレーション

実行

$knex migrate:latest

ロールバック

$ knex migrate:rollback

シード

ファイル作成

$knex seed:make test_users
Using environment: development
Created seed file: ./db/seeds/test_users.js

実行

$knex seed:run

Herokuでの実行

$heroku run knex migrate:latest --app app-name

Viewing all articles
Browse latest Browse all 8829

Trending Articles