UNPKG

12.2 kBMarkdownView Raw
1# bookshelf.js
2
3[![NPM Version](https://img.shields.io/npm/v/bookshelf.svg?style=flat)](https://www.npmjs.com/package/bookshelf)
4[![Build Status](https://api.travis-ci.org/bookshelf/bookshelf.svg?branch=master)](https://travis-ci.org/bookshelf/bookshelf)
5[![Dependency Status](https://david-dm.org/bookshelf/bookshelf/status.svg)](https://david-dm.org/bookshelf/bookshelf)
6[![devDependency Status](https://david-dm.org/bookshelf/bookshelf/dev-status.svg)](https://david-dm.org/bookshelf/bookshelf?type=dev)
7
8Bookshelf is a JavaScript ORM for Node.js, built on the [Knex](http://knexjs.org) SQL query builder. It features both Promise-based and traditional callback interfaces, transaction support, eager/nested-eager relation loading, polymorphic associations, and support for one-to-one, one-to-many, and many-to-many relations.
9
10It is designed to work with PostgreSQL, MySQL, and SQLite3.
11
12[Website and documentation](http://bookshelfjs.org). The project is [hosted on GitHub](http://github.com/bookshelf/bookshelf/), and has a comprehensive [test suite](https://travis-ci.org/bookshelf/bookshelf).
13
14## Introduction
15
16Bookshelf aims to provide a simple library for common tasks when querying databases in JavaScript, and forming relations between these objects, taking a lot of ideas from the [Data Mapper Pattern](http://en.wikipedia.org/wiki/Data_mapper_pattern).
17
18With a concise, literate codebase, Bookshelf is simple to read, understand, and extend. It doesn't force you to use any specific validation scheme, and provides flexible, efficient relation/nested-relation loading and first-class transaction support.
19
20It's a lean object-relational mapper, allowing you to drop down to the raw Knex interface whenever you need a custom query that doesn't quite fit with the stock conventions.
21
22## Installation
23
24You'll need to install a copy of [Knex](http://knexjs.org/), and either `mysql`, `pg`, or `sqlite3` from npm.
25
26```js
27$ npm install knex
28$ npm install bookshelf
29
30# Then add one of the following:
31$ npm install pg
32$ npm install mysql
33$ npm install sqlite3
34```
35
36The Bookshelf library is initialized by passing an initialized [Knex](http://knexjs.org/) client instance. The [Knex documentation](http://knexjs.org/) provides a number of examples for different databases.
37
38```js
39// Setting up the database connection
40const knex = require('knex')({
41 client: 'mysql',
42 connection: {
43 host : '127.0.0.1',
44 user : 'your_database_user',
45 password : 'your_database_password',
46 database : 'myapp_test',
47 charset : 'utf8'
48 }
49})
50const bookshelf = require('bookshelf')(knex)
51
52// Defining models
53const User = bookshelf.model('User', {
54 tableName: 'users'
55})
56```
57
58This initialization should likely only ever happen once in your application. As it creates a connection pool for the current database, you should use the `bookshelf` instance returned throughout your library. You'll need to store this instance created by the initialize somewhere in the application so you can reference it. A common pattern to follow is to initialize the client in a module so you can easily reference it later:
59
60```js
61// In a file named, e.g. bookshelf.js
62const knex = require('knex')(dbConfig)
63module.exports = require('bookshelf')(knex)
64
65// elsewhere, to use the bookshelf client:
66const bookshelf = require('./bookshelf')
67
68const Post = bookshelf.model('Post', {
69 // ...
70})
71```
72
73## Examples
74
75Here is an example to get you started:
76
77```js
78const knex = require('knex')({
79 client: 'mysql',
80 connection: process.env.MYSQL_DATABASE_CONNECTION
81})
82const bookshelf = require('bookshelf')(knex)
83
84const User = bookshelf.model('User', {
85 tableName: 'users',
86 posts() {
87 return this.hasMany(Posts)
88 }
89})
90
91const Post = bookshelf.model('Post', {
92 tableName: 'posts',
93 tags() {
94 return this.belongsToMany(Tag)
95 }
96})
97
98const Tag = bookshelf.model('Tag', {
99 tableName: 'tags'
100})
101
102new User({id: 1}).fetch({withRelated: ['posts.tags']}).then((user) => {
103 console.log(user.related('posts').toJSON())
104}).catch((error) => {
105 console.error(error)
106})
107```
108
109## Official Plugins
110
111* [Virtuals](https://github.com/bookshelf/virtuals-plugin): Define virtual properties on your model to compute new values.
112* [Case Converter](https://github.com/bookshelf/case-converter-plugin): Handles the conversion between the database's snake_cased and a model's camelCased properties automatically.
113* [Processor](https://github.com/bookshelf/processor-plugin): Allows defining custom processor functions that handle transformation of values whenever they are `.set()` on a model.
114
115## Community plugins
116
117* [bookshelf-cascade-delete](https://github.com/seegno/bookshelf-cascade-delete) - Cascade delete related models on destroy.
118* [bookshelf-json-columns](https://github.com/seegno/bookshelf-json-columns) - Parse and stringify JSON columns on save and fetch instead of manually define hooks for each model (PostgreSQL and SQLite).
119* [bookshelf-mask](https://github.com/seegno/bookshelf-mask) - Similar to the functionality of the {@link Model#visible} attribute but supporting multiple scopes, masking models and collections using the [json-mask](https://github.com/nemtsov/json-mask) API.
120* [bookshelf-schema](https://github.com/bogus34/bookshelf-schema) - A plugin for handling fields, relations, scopes and more.
121* [bookshelf-signals](https://github.com/bogus34/bookshelf-signals) - A plugin that translates Bookshelf events to a central hub.
122* [bookshelf-paranoia](https://github.com/estate/bookshelf-paranoia) - Protect your database from data loss by soft deleting your rows.
123* [bookshelf-uuid](https://github.com/estate/bookshelf-uuid) - Automatically generates UUIDs for your models.
124* [bookshelf-modelbase](https://github.com/bsiddiqui/bookshelf-modelbase) - An alternative to extend `Model`, adding timestamps, attribute validation and some native CRUD methods.
125* [bookshelf-advanced-serialization](https://github.com/sequiturs/bookshelf-advanced-serialization) - A more powerful visibility plugin, supporting serializing models and collections according to access permissions, application context, and after ensuring relations have been loaded.
126* [bookshelf-plugin-mode](https://github.com/popodidi/bookshelf-plugin-mode) - Plugin inspired by the functionality of the {@link Model#visible} attribute, allowing to specify different modes with corresponding visible/hidden fields of model.
127* [bookshelf-secure-password](https://github.com/venables/bookshelf-secure-password) - A plugin for easily securing passwords using bcrypt.
128* [bookshelf-default-select](https://github.com/DJAndries/bookshelf-default-select) - Enables default column selection for models. Inspired by the functionality of the {@link Model#visible} attribute, but operates on the database level.
129* [bookshelf-ez-fetch](https://github.com/DJAndries/bookshelf-ez-fetch) - Convenient fetching methods which allow for compact filtering, relation selection and error handling.
130* [bookshelf-manager](https://github.com/ericclemmons/bookshelf-manager) - Model & Collection manager to make it easy to create & save deep, nested JSON structures from API requests.
131
132## Support
133
134Have questions about the library? Come join us in the [#bookshelf freenode IRC channel](http://webchat.freenode.net/?channels=bookshelf) for support on [knex.js](http://knexjs.org/) and bookshelf.js, or post an issue on [Stack Overflow](http://stackoverflow.com/questions/tagged/bookshelf.js).
135
136## Contributing
137
138If you want to contribute to Bookshelf you'll usually want to report an issue or submit a
139pull-request. For this purpose the [online repository](https://github.com/bookshelf/bookshelf/) is
140available on GitHub.
141
142For further help setting up your local development environment or learning how you can contribute to
143Bookshelf you should read the [Contributing document](https://github.com/bookshelf/bookshelf/blob/master/.github/CONTRIBUTING.md)
144available on GitHub.
145
146## F.A.Q.
147
148### Can I use standard node.js style callbacks?
149
150Yes, you can call `.asCallback(function(err, resp) {` on any database operation method and use the standard `(err, result)` style callback interface if you prefer.
151
152### My relations don't seem to be loading, what's up?
153
154Make sure to check that the type is correct for the initial parameters passed to the initial model being fetched. For example `new Model({id: '1'}).load([relations...])` will not return the same as `new Model({id: 1}).load([relations...])` - notice that the id is a string in one case and a number in the other. This can be a common mistake if retrieving the id from a url parameter.
155
156This is only an issue if you're eager loading data with load without first fetching the original model. `new Model({id: '1'}).fetch({withRelated: [relations...]})` should work just fine.
157
158### My process won't exit after my script is finished, why?
159
160The issue here is that Knex, the database abstraction layer used by Bookshelf, uses connection pooling and thus keeps the database connection open. If you want your process to exit after your script has finished, you will have to call `.destroy(cb)` on the `knex` property of your `Bookshelf` instance or on the `Knex` instance passed during initialization. More information about connection pooling can be found over at the [Knex docs](http://knexjs.org/#Installation-pooling).
161
162### How do I debug?
163
164If you pass `debug: true` in the options object to your `knex` initialize call, you can see all of the query calls being made. You can also pass that same option to all methods that access the database, like `model.fetch()` or `model.destroy()`. Examples:
165
166```js
167// Turning on debug mode for all queries
168const knex = require('knex')({
169 debug: true,
170 client: 'mysql',
171 connection: process.env.MYSQL_DATABASE_CONNECTION
172})
173const bookshelf = require('bookshelf')(knex)
174
175// Debugging a single query
176new User({id: 1}).fetch({debug: true, withRelated: ['posts.tags']}).then(user => {
177 // ...
178})
179```
180
181Sometimes you need to dive a bit further into the various calls and see what all is going on behind the scenes. You can use [node-inspector](https://github.com/dannycoates/node-inspector), which allows you to debug code with `debugger` statements like you would in the browser.
182
183Bookshelf uses its own copy of the `bluebird` Promise library. You can read up [here](http://bluebirdjs.com/docs/api/promise.config.html) for more on debugging Promises.
184
185Adding the following block at the start of your application code will catch any errors not otherwise caught in the normal Promise chain handlers, which is very helpful in debugging:
186
187```js
188process.stderr.on('data', (data) => {
189 console.log(data)
190})
191```
192
193### How do I run the test suite?
194
195See the [CONTRIBUTING](https://github.com/bookshelf/bookshelf/blob/master/.github/CONTRIBUTING.md#running-the-tests)
196document on GitHub.
197
198### Can I use Bookshelf outside of Node.js?
199
200While it primarily targets Node.js, all dependencies are browser compatible, and it could be adapted to work with other javascript environments supporting a sqlite3 database, by providing a custom [Knex adapter](http://knexjs.org/#Adapters). No such adapter exists though.
201
202### Which open-source projects are using Bookshelf?
203
204We found the following projects using Bookshelf, but there can be more:
205
206* [Ghost](https://ghost.org/) (A blogging platform) uses bookshelf. [[Link](https://github.com/TryGhost/Ghost/tree/master/core/server/models)]
207* [Soapee](http://soapee.com/) (Soap Making Community and Resources) uses bookshelf. [[Link](https://github.com/nazar/soapee-api/tree/master/src/models)]
208* [NodeZA](http://nodeza.co.za/) (Node.js social platform for developers in South Africa) uses bookshelf. [[Link](https://github.com/qawemlilo/nodeza/tree/master/models)]
209* [Sunday Cook](https://github.com/sunday-cooks/sunday-cook) (A social cooking event platform) uses bookshelf. [[Link](https://github.com/sunday-cooks/sunday-cook/tree/master/server/bookshelf)]
210* [FlyptoX](http://www.flyptox.com/) (Open-source Node.js cryptocurrency exchange) uses bookshelf. [[Link](https://github.com/FlipSideHR/FlyptoX/tree/master/server/models)]
211* And of course, everything on [here](https://www.npmjs.com/browse/depended/bookshelf) use bookshelf too.