forked from bookshelf/bookshelf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
18308 lines (6887 loc) · 369 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="icon" href="docs/images/favicon.ico" />
<link rel="canonical" href="http://bookshelfjs.org" />
<title>Bookshelf.js</title>
<!--
._. ._.
| | ______ _ _ _ __ | |
| | | ___ \ | | | | | |/ _| | |
| | | |_/ / ___ ___ | | _____| |__ ___| | |_ | |
| | | ___ \/ _ \ / _ \| |/ / __| '_ \ / _ \ | _| | |
| | | |_/ / (_) | (_) | <\__ \ | | | __/ | | | |
| |____\____/_\___/_\___/|_|\_\___/_|_|_|\___|_|_|_______| |
| |
\________\ /__________________________________\ /________/
\/ \/
-->
<script src="docs/scripts/prettify/prettify.js"></script>
<script src="docs/scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Import fonts from Open Font Library -->
<link rel="stylesheet" media="screen" href="http://openfontlibrary.org/face/carlito" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" media="screen" href="http://openfontlibrary.org/face/average-mono" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" media="screen" href="http://openfontlibrary.org/face/noto-serif" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<link type="text/css" rel="stylesheet" href="docs/styles/main.css">
</head>
<body class="minami">
<a class="fork-me" href="https://github.com/tgriesser/bookshelf">
Fork me on GitHub
</a>
<!--
Not sure what this is.
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
-->
<nav class="sidebar">
<a href="index.html#">
<header class="nav-header">
<img class="nav-logo" src="docs/images/bookshelf-icon.svg" />
<h1>Bookshelf.js</h1>
</header>
</a>
<ul class="readme"><li><h3><a href="#introduction">Introduction</a></h3></li>
<li><h3><a href="#installation">Installation</a></h3></li>
<li><h3><a href="#examples">Examples</a></h3></li>
<li><h3><a href="#plugins">Plugins</a></h3></li>
<li><h3><a href="#support">Support</a></h3></li>
<li><h3><a href="#faq">F.A.Q.</a></h3></li></ul><ul class="changelog"><li><h3><a href="#changelog">Change log</a></h3></li></ul><ul class="main"><li><h3><a href="#associations">Associations</a></h3><ul class="sections"><li><a href="#one-to-one">One-to-one</a></li><li><a href="#one-to-many">One-to-many</a></li><li><a href="#many-to-many">Many-to-many</a></li><li><a href="#polymorphic">Polymorphic</a></li></ul></li><li><h3><a href="#section-Bookshelf">Bookshelf</a></h3><h4><a href="#Bookshelf-subsection-construction">Construction</a></h4><ul class="construction"><li><a href="#Bookshelf">Bookshelf</a></li></ul><h4><a href="#Bookshelf-subsection-members">Members</a></h4><ul class="members"><li><a href="#Bookshelf-instance-knex">knex</a></li></ul><h4><a href="#Bookshelf-subsection-methods">Methods</a></h4><ul class="methods"><li><a href="#Bookshelf-instance-transaction">transaction</a></li></ul></li><li><h3><a href="#section-Model">Model</a></h3><h4><a href="#Model-subsection-construction">Construction</a></h4><ul class="construction"><li><a href="#Model">Model</a></li><li><a href="#Model-instance-initialize">initialize</a></li></ul><h4><a href="#Model-subsection-static">Static</a></h4><ul class="static"><li><a href="#Model-static-collection">collection</a></li><li><a href="#Model-static-count">count</a></li><li><a href="#Model-static-extend">extend</a></li><li><a href="#Model-static-fetchAll">fetchAll</a></li><li><a href="#Model-static-forge">forge</a></li></ul><h4><a href="#Model-subsection-members">Members</a></h4><ul class="members"><li><a href="#Model-instance-hasTimestamps">hasTimestamps</a></li><li><a href="#Model-instance-idAttribute">idAttribute</a></li><li><a href="#Model-instance-tableName">tableName</a></li></ul><h4><a href="#Model-subsection-methods">Methods</a></h4><ul class="methods"><li><a href="#Model-instance-belongsTo">belongsTo</a></li><li><a href="#Model-instance-belongsToMany">belongsToMany</a></li><li><a href="#Model-instance-clear">clear</a></li><li><a href="#Model-instance-clone">clone</a></li><li><a href="#Model-instance-count">count</a></li><li><a href="#Model-instance-destroy">destroy</a></li><li><a href="#Model-instance-escape">escape</a></li><li><a href="#Model-instance-fetch">fetch</a></li><li><a href="#Model-instance-fetchAll">fetchAll</a></li><li><a href="#Model-instance-format">format</a></li><li><a href="#Model-instance-get">get</a></li><li><a href="#Model-instance-has">has</a></li><li><a href="#Model-instance-hasChanged">hasChanged</a></li><li><a href="#Model-instance-hasMany">hasMany</a></li><li><a href="#Model-instance-hasOne">hasOne</a></li><li><a href="#Model-instance-isNew">isNew</a></li><li><a href="#Model-instance-load">load</a></li><li><a href="#Model-instance-morphMany">morphMany</a></li><li><a href="#Model-instance-morphOne">morphOne</a></li><li><a href="#Model-instance-morphTo">morphTo</a></li><li><a href="#Model-instance-off">off</a></li><li><a href="#Model-instance-on">on</a></li><li><a href="#Model-instance-once">once</a></li><li><a href="#Model-instance-parse">parse</a></li><li><a href="#Model-instance-previous">previous</a></li><li><a href="#Model-instance-previousAttributes">previousAttributes</a></li><li><a href="#Model-instance-query">query</a></li><li><a href="#Model-instance-refresh">refresh</a></li><li><a href="#Model-instance-related">related</a></li><li><a href="#Model-instance-resetQuery">resetQuery</a></li><li><a href="#Model-instance-save">save</a></li><li><a href="#Model-instance-serialize">serialize</a></li><li><a href="#Model-instance-set">set</a></li><li><a href="#Model-instance-through">through</a></li><li><a href="#Model-instance-timestamp">timestamp</a></li><li><a href="#Model-instance-toJSON">toJSON</a></li><li><a href="#Model-instance-trigger">trigger</a></li><li><a href="#Model-instance-triggerThen">triggerThen</a></li><li><a href="#Model-instance-unset">unset</a></li><li><a href="#Model-instance-where">where</a></li></ul><h4><a href="#Model-subsection-lodash-methods">Lodash Methods</a></h4><ul class="lodash-methods"><li><a href="#Model-instance-invert">invert</a></li><li><a href="#Model-instance-keys">keys</a></li><li><a href="#Model-instance-omit">omit</a></li><li><a href="#Model-instance-pairs">pairs</a></li><li><a href="#Model-instance-pick">pick</a></li><li><a href="#Model-instance-values">values</a></li></ul><h4><a href="#Model-subsection-events">Events</a></h4><ul class="events"><li><a href="#Model-event-created">created</a></li><li><a href="#Model-event-creating">creating</a></li><li><a href="#Model-event-destroyed">destroyed</a></li><li><a href="#Model-event-destroying">destroying</a></li><li><a href="#Model-event-fetched">fetched</a></li><li><a href="#Model-event-fetching">fetching</a></li><li><a href="#Model-event-saved">saved</a></li><li><a href="#Model-event-saving">saving</a></li><li><a href="#Model-event-updated">updated</a></li><li><a href="#Model-event-updating">updating</a></li></ul></li><li><h3><a href="#section-Model-static-NoRowsDeletedError">NoRowsDeletedError</a></h3><h4><a href="#Model-static-NoRowsDeletedError-subsection-construction">Construction</a></h4><ul class="construction"><li><a href="#Model-static-NoRowsDeletedError">NoRowsDeletedError</a></li></ul></li><li><h3><a href="#section-Model-static-NoRowsUpdatedError">NoRowsUpdatedError</a></h3><h4><a href="#Model-static-NoRowsUpdatedError-subsection-construction">Construction</a></h4><ul class="construction"><li><a href="#Model-static-NoRowsUpdatedError">NoRowsUpdatedError</a></li></ul></li><li><h3><a href="#section-Model-static-NotFoundError">NotFoundError</a></h3><h4><a href="#Model-static-NotFoundError-subsection-construction">Construction</a></h4><ul class="construction"><li><a href="#Model-static-NotFoundError">NotFoundError</a></li></ul></li><li><h3><a href="#section-Collection">Collection</a></h3><h4><a href="#Collection-subsection-construction">Construction</a></h4><ul class="construction"><li><a href="#Collection">Collection</a></li><li><a href="#Collection-instance-initialize">initialize</a></li></ul><h4><a href="#Collection-subsection-static">Static</a></h4><ul class="static"><li><a href="#Collection-static-extend">extend</a></li><li><a href="#Collection-static-forge">forge</a></li></ul><h4><a href="#Collection-subsection-methods">Methods</a></h4><ul class="methods"><li><a href="#Collection-instance-add">add</a></li><li><a href="#Collection-instance-at">at</a></li><li><a href="#Collection-instance-attach">attach</a></li><li><a href="#Collection-instance-clone">clone</a></li><li><a href="#Collection-instance-count">count</a></li><li><a href="#Collection-instance-create">create</a></li><li><a href="#Collection-instance-detach">detach</a></li><li><a href="#Collection-instance-fetch">fetch</a></li><li><a href="#Collection-instance-fetchOne">fetchOne</a></li><li><a href="#Collection-instance-findWhere">findWhere</a></li><li><a href="#Collection-instance-get">get</a></li><li><a href="#Collection-instance-invokeThen">invokeThen</a></li><li><a href="#Collection-instance-load">load</a></li><li><a href="#Collection-instance-off">off</a></li><li><a href="#Collection-instance-on">on</a></li><li><a href="#Collection-instance-once">once</a></li><li><a href="#Collection-instance-parse">parse</a></li><li><a href="#Collection-instance-pluck">pluck</a></li><li><a href="#Collection-instance-pop">pop</a></li><li><a href="#Collection-instance-push">push</a></li><li><a href="#Collection-instance-query">query</a></li><li><a href="#Collection-instance-reduceThen">reduceThen</a></li><li><a href="#Collection-instance-remove">remove</a></li><li><a href="#Collection-instance-reset">reset</a></li><li><a href="#Collection-instance-resetQuery">resetQuery</a></li><li><a href="#Collection-instance-serialize">serialize</a></li><li><a href="#Collection-instance-set">set</a></li><li><a href="#Collection-instance-shift">shift</a></li><li><a href="#Collection-instance-slice">slice</a></li><li><a href="#Collection-instance-through">through</a></li><li><a href="#Collection-instance-toJSON">toJSON</a></li><li><a href="#Collection-instance-trigger">trigger</a></li><li><a href="#Collection-instance-triggerThen">triggerThen</a></li><li><a href="#Collection-instance-unshift">unshift</a></li><li><a href="#Collection-instance-updatePivot">updatePivot</a></li><li><a href="#Collection-instance-where">where</a></li><li><a href="#Collection-instance-withPivot">withPivot</a></li></ul><h4><a href="#Collection-subsection-lodash-methods">Lodash Methods</a></h4><ul class="lodash-methods"><li><a href="#Collection-instance-all">all</a></li><li><a href="#Collection-instance-any">any</a></li><li><a href="#Collection-instance-chain">chain</a></li><li><a href="#Collection-instance-collect">collect</a></li><li><a href="#Collection-instance-contains">contains</a></li><li><a href="#Collection-instance-countBy">countBy</a></li><li><a href="#Collection-instance-detect">detect</a></li><li><a href="#Collection-instance-difference">difference</a></li><li><a href="#Collection-instance-drop">drop</a></li><li><a href="#Collection-instance-each">each</a></li><li><a href="#Collection-instance-every">every</a></li><li><a href="#Collection-instance-filter">filter</a></li><li><a href="#Collection-instance-find">find</a></li><li><a href="#Collection-instance-first">first</a></li><li><a href="#Collection-instance-foldl">foldl</a></li><li><a href="#Collection-instance-foldr">foldr</a></li><li><a href="#Collection-instance-forEach">forEach</a></li><li><a href="#Collection-instance-groupBy">groupBy</a></li><li><a href="#Collection-instance-head">head</a></li><li><a href="#Collection-instance-include">include</a></li><li><a href="#Collection-instance-indexOf">indexOf</a></li><li><a href="#Collection-instance-initial">initial</a></li><li><a href="#Collection-instance-inject">inject</a></li><li><a href="#Collection-instance-invoke">invoke</a></li><li><a href="#Collection-instance-isEmpty">isEmpty</a></li><li><a href="#Collection-instance-last">last</a></li><li><a href="#Collection-instance-lastIndexOf">lastIndexOf</a></li><li><a href="#Collection-instance-map">map</a></li><li><a href="#Collection-instance-max">max</a></li><li><a href="#Collection-instance-min">min</a></li><li><a href="#Collection-instance-reduce">reduce</a></li><li><a href="#Collection-instance-reduceRight">reduceRight</a></li><li><a href="#Collection-instance-reject">reject</a></li><li><a href="#Collection-instance-rest">rest</a></li><li><a href="#Collection-instance-select">select</a></li><li><a href="#Collection-instance-shuffle">shuffle</a></li><li><a href="#Collection-instance-size">size</a></li><li><a href="#Collection-instance-some">some</a></li><li><a href="#Collection-instance-sortBy">sortBy</a></li><li><a href="#Collection-instance-tail">tail</a></li><li><a href="#Collection-instance-take">take</a></li><li><a href="#Collection-instance-toArray">toArray</a></li><li><a href="#Collection-instance-without">without</a></li></ul><h4><a href="#Collection-subsection-events">Events</a></h4><ul class="events"><li><a href="#Collection-event-fetched">fetched</a></li></ul></li><li><h3><a href="#section-Collection-static-EmptyError">EmptyError</a></h3><h4><a href="#Collection-static-EmptyError-subsection-construction">Construction</a></h4><ul class="construction"><li><a href="#Collection-static-EmptyError">EmptyError</a></li></ul></li><li><h3><a href="#section-Events">Events</a></h3><h4><a href="#Events-subsection-construction">Construction</a></h4><ul class="construction"><li><a href="#Events">Events</a></li></ul><h4><a href="#Events-subsection-methods">Methods</a></h4><ul class="methods"><li><a href="#Events-instance-off">off</a></li><li><a href="#Events-instance-on">on</a></li><li><a href="#Events-instance-once">once</a></li><li><a href="#Events-instance-trigger">trigger</a></li><li><a href="#Events-instance-triggerThen">triggerThen</a></li></ul></li></ul>
</nav>
<div class="main-container ">
<div class="main-column">
<section class="readme">
<article><h1 id="a-hrefhttpbookshelfjsorgbookshelfjsa-a-hrefhttpstravisciorgtgriesserbookshelfimg-srchttpstravisciorgtgriesserbookshelfsvgbranchmaster-altbuild-statusa"><a href="http://bookshelfjs.org">bookshelf.js</a> <a href="https://travis-ci.org/tgriesser/bookshelf"><img src="https://travis-ci.org/tgriesser/bookshelf.svg?branch=master" alt="Build Status"></a></h1><p>Bookshelf is a JavaScript ORM for Node.js, built on the <a href="http://knexjs.org">Knex</a> SQL query builder. Featuring both promise based and traditional callback interfaces, providing transaction support, eager/nested-eager relation loading, polymorphic associations, and support for one-to-one, one-to-many, and many-to-many relations.</p>
<p>It is designed to work well with PostgreSQL, MySQL, and SQLite3.</p>
<p><a href="http://bookshelfjs.org">Website and documentation</a>. The project is <a href="http://github.com/tgriesser/bookshelf/">hosted on GitHub</a>, and has a comprehensive <a href="https://travis-ci.org/tgriesser/bookshelf">test suite</a>.</p>
<h2 id="introduction">Introduction</h2><p>Bookshelf 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 the <a href="http://en.wikipedia.org/wiki/Data_mapper_pattern">Data Mapper Pattern</a>.</p>
<p>With a concise, literate codebase, Bookshelf is simple to read, understand, and extend. It doesn't force you to use any specific validation scheme, provides flexible and efficient relation/nested-relation loading, and first class transaction support.</p>
<p>It'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.</p>
<h2 id="installation">Installation</h2><p>You'll need to install a copy of <a href="http://knexjs.org/">knex.js</a>, and either mysql, pg, or sqlite3 from npm.</p>
<pre class="prettyprint source lang-js"><code>$ npm install knex --save
$ npm install bookshelf --save
# Then add one of the following:
$ npm install pg
$ npm install mysql
$ npm install mariasql
$ npm install sqlite3</code></pre><p>The Bookshelf library is initialized by passing an initialized <a href="http://knexjs.org/">Knex</a> client instance. The <a href="http://knexjs.org/">knex documentation</a> provides a number of examples for different databases.</p>
<pre class="prettyprint source lang-js"><code>var knex = require('knex')({
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test',
charset : 'utf8'
}
});
var bookshelf = require('bookshelf')(knex);
var User = bookshelf.Model.extend({
tableName: 'users'
});</code></pre><p>This initialization should likely only ever happen once in your application. As it creates a connection pool for the current database, you should use the <code>bookshelf</code> 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:</p>
<pre class="prettyprint source lang-js"><code>// In a file named something like bookshelf.js
var knex = require('knex')(dbConfig);
module.exports = require('bookshelf')(knex);
// elsewhere, to use the bookshelf client:
var bookshelf = require('./bookshelf');
var Post = bookshelf.Model.extend({
// ...
});</code></pre><h2 id="examples">Examples</h2><p>Here is an example to get you started:</p>
<pre class="prettyprint source lang-js"><code>var knex = require('knex')({client: 'mysql', connection: process.env.MYSQL_DATABASE_CONNECTION });
var bookshelf = require('bookshelf')(knex);
var User = bookshelf.Model.extend({
tableName: 'users',
posts: function() {
return this.hasMany(Posts);
}
});
var Posts = bookshelf.Model.extend({
tableName: 'messages',
tags: function() {
return this.belongsToMany(Tag);
}
});
var Tag = bookshelf.Model.extend({
tableName: 'tags'
})
User.where('id', 1).fetch({withRelated: ['posts.tags']}).then(function(user) {
console.log(user.related('posts').toJSON());
}).catch(function(err) {
console.error(err);
});</code></pre><h2 id="plugins">Plugins</h2><ul>
<li><a href="https://github.com/tgriesser/bookshelf/wiki/Plugin:-Model-Registry">Registry</a>: Register models in a central location so that you can refer to them using a string in relations instead of having to require it every time. Helps deal with the challenges of circular module dependencies in Node.</li>
<li><a href="https://github.com/tgriesser/bookshelf/wiki/Plugin:-Virtuals">Virtuals</a>: Define virtual properties on your model to compute new values.</li>
<li><a href="https://github.com/tgriesser/bookshelf/wiki/Plugin:-Visibility">Visibility</a>: Specify a whitelist/blacklist of model attributes when serialized toJSON.</li>
</ul>
<h2 id="support">Support</h2><p>Have questions about the library? Come join us in the <a href="http://webchat.freenode.net/?channels=bookshelf">#bookshelf freenode IRC channel</a> for support on <a href="http://knexjs.org/">knex.js</a> and bookshelf.js, or post an issue on <a href="http://stackoverflow.com/questions/tagged/bookshelf.js">Stack Overflow</a> or in the GitHub <a href="https://github.com/tgriesser/bookshelf/issues">issue tracker</a>.</p>
<h2 id="faq">F.A.Q.</h2><h3 id="can-i-use-standard-nodejs-style-callbacks">Can I use standard node.js style callbacks?</h3><p>Yes - you can call <code>.asCallback(function(err, resp) {</code> on any "sync" method and use the standard <code>(err, result)</code> style callback interface if you prefer.</p>
<h3 id="my-relations-dont-seem-to-be-loading-whats-up">My relations don't seem to be loading, what's up?</h3><p>Make sure you check that the type is correct for the initial parameters passed to the initial model being fetched. For example <code>new Model({id: '1'}).load([relations...])</code> will not return the same as <code>Model({id: 1}).load([relations...])</code> - 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.</p>
<p>This is only an issue if you're eager loading data with load without first fetching the original model. <code>Model({id: '1'}).fetch({withRelated: [relations...]})</code> should work just fine.</p>
<h3 id="my-process-wont-exit-after-my-script-is-finished-why">My process won't exit after my script is finished, why?</h3><p>The 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 <code>.destroy(cb)</code> on the <code>knex</code> property of your <code>Bookshelf</code> instance or on the <code>Knex</code> instance passed during initialization. More information about connection pooling can be found over at the <a href="http://knexjs.org/#Installation-pooling">Knex docs</a>.</p>
<h3 id="how-do-i-debug">How do I debug?</h3><p>If you pass <code>{debug: true}</code> as one of the options in your initialize settings, you can see all of the query calls being made. Sometimes you need to dive a bit further into the various calls and see what all is going on behind the scenes. I'd recommend <a href="https://github.com/dannycoates/node-inspector">node-inspector</a>, which allows you to debug code with <code>debugger</code> statements like you would in the browser.</p>
<p>Bookshelf uses its own copy of the "bluebird" promise library, you can read up here for more on debugging these promises... but in short, adding:</p>
<pre class="prettyprint source"><code>process.stderr.on('data', function(data) {
console.log(data);
});</code></pre><p>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.</p>
<h3 id="how-do-i-run-the-test-suite">How do I run the test suite?</h3><p>The test suite looks for an environment variable called <code>BOOKSHELF_TEST</code> for the path to the database configuration. If you run the following command: <code>$ export BOOKSHELF_TEST='/path/to/your/bookshelf_config.js'</code>, replacing with the path to your config file, and the config file is valid, the test suite should run with npm test.</p>
<p>Also note that you will have to create the appropriate database(s) for the test suite to run. For example, with MySQL, you'll need to run the command <code>create database bookshelf_test;</code> in addition to exporting the correct test settings prior to running the test suite.</p>
<h3 id="can-i-use-bookshelf-outside-of-nodejs">Can I use Bookshelf outside of Node.js?</h3><p>While 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 <a href="http://knexjs.org/#Adapters">Knex adapter</a>.</p>
<h3 id="which-opensource-projects-are-using-bookshelf">Which open-source projects are using Bookshelf?</h3><p>We found the following projects using Bookshelf, but there can be more:</p>
<ul>
<li><a href="https://ghost.org/">Ghost</a> (A blogging platform) uses bookshelf. [<a href="https://github.com/TryGhost/Ghost/tree/master/core/server/models">Link</a>]</li>
<li><a href="http://soapee.com/">Soapee</a> (Soap Making Community and Resources) uses bookshelf. [<a href="https://github.com/nazar/soapee-api/tree/master/src/models">Link</a>]</li>
<li><a href="http://nodeza.co.za/">NodeZA</a> (Node.js social platform for developers in South Africa) uses bookshelf. [<a href="https://github.com/qawemlilo/nodeza/tree/master/models">Link</a>]</li>
<li><a href="https://github.com/sunday-cooks/sunday-cook">Sunday Cook</a> (A social cooking event platform) uses bookshelf. [<a href="https://github.com/sunday-cooks/sunday-cook/tree/master/server/bookshelf">Link</a>]</li>
<li><a href="http://www.flyptox.com/">FlyptoX</a> (Open-source Node.js cryptocurrency exchange) uses bookshelf. [<a href="https://github.com/FlipSideHR/FlyptoX/tree/master/server/models">Link</a>]</li>
<li>And of course, everything on <a href="https://www.npmjs.com/browse/depended/bookshelf">here</a> use bookshelf too.</li>
</ul></article>
</section>
<section class="tutorials">
<article class="tutorial">
<h2 id="associations">Associations</h2>
<p>Bookshelf handles one-to-one, one-to-many, and many-to-many associations by defining relationships on models.</p>
<section class="sections">
<h3 id="one-to-one">One-to-one</h3>
<p>One-to-one associations can be created with <a href="#Model-instance-belongsTo"><code>belongsTo</code></a>, <a href="#Model-instance-hasOne"><code>hasOne</code></a>, and <a href="#Model-instance-morphOne"><code>morphOne</code></a> relation types.</p>
<pre class="prettyprint source"><code>var Book, Summary;
Book = bookshelf.Model.extend({
tableName: 'books',
summary: function() {
return this.hasOne(Summary);
}
});
Summary = bookshelf.Model.extend({
tableName: 'summaries',
book: function() {
return this.belongsTo(Book);
}
});</code></pre><p>A Knex migration for the above relationship could be created with:</p>
<pre class="prettyprint source"><code>exports.up = function(knex, Promise) {
return knex.schema.createTable('books', function(table) {
table.increments('id').primary();
table.string('name');
}).createTable('summaries', function(table) {
table.increments('id').primary();
table.string('details');
table.integer('book_id').unique().references('books.id');
});
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable('books')
.dropTable('summaries');
};</code></pre>
</section>
<section class="sections">
<h3 id="one-to-many">One-to-many</h3>
<p>One-to-many associations can be created with <a href="#Model-instance-belongsTo"><code>belongsTo</code></a>, <a href="#Model-instance-hasMany"><code>hasMany</code></a>, <a href="#Model-instance-morphMany"><code>morphMany</code></a> / <a href="#Model-instance-morphTo"><code>morphTo</code></a>, and some of the <a href="#Model-instance-through"><code>through</code></a> relation types.</p>
<pre class="prettyprint source"><code>var Book = bookshelf.Model.extend({
tableName: 'books',
pages: function() {
return this.hasMany(Page);
}
});
var Page = bookshelf.Model.extend({
tableName: 'pages',
book: function() {
return this.belongsTo(Book);
}
});</code></pre><p>A Knex migration for the above relationship could be created with:</p>
<pre class="prettyprint source"><code>exports.up = function(knex, Promise) {
return knex.schema.createTable('books', function(table) {
table.increments('id').primary();
table.string('name');
}).createTable('pages', function(table) {
table.increments('id').primary();
table.string('content');
table.integer('book_id').references('books.id')
});
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable('books')
.dropTable('pages');
};</code></pre>
</section>
<section class="sections">
<h3 id="many-to-many">Many-to-many</h3>
<p>Many-to-many associations can be created with <a href="#Model-instance-belongsToMany"><code>belongsToMany</code></a>, and <a href="#Model-instance-through"><code>through</code></a> relation types.</p>
<pre class="prettyprint source"><code>var Book = bookshelf.Model.extend({
tableName: 'books',
authors: function() {
return this.belongsToMany(Author);
}
});
var Author = bookshelf.Model.extend({
tableName: 'authors',
books: function() {
return this.belongsToMany(Book);
}
});</code></pre><p>A Knex migration for the above relationship could be created with:</p>
<pre class="prettyprint source"><code>exports.up = function(knex, Promise) {
return knex.schema.createTable('books', function(table) {
table.increments('id').primary();
table.string('name');
}).createTable('authors', function(table) {
table.increments('id').primary();
table.string('name');
}).createTable('authors_books', function(table) {
table.integer('author_id').references('authors.id');
table.integer('book_id').references('books.id');
});
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable('books')
.dropTable('authors')
.dropTable('authors_books');
};</code></pre>
</section>
<section class="sections">
<h3 id="polymorphic">Polymorphic</h3>
<p>With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a photo model that belongs to either a <code>Site</code> model or a <code>Post</code> model. Here’s how this could be declared:</p>
<pre class="prettyprint source"><code>var Site = bookshelf.Model.extend({
tableName: 'sites',
photo: function() {
return this.morphOne(Photo, 'imageable');
}
});
var Post = bookshelf.Model.extend({
tableName: 'posts',
photos: function() {
return this.morphMany(Photo, 'imageable');
}
});
var Photo = bookshelf.Model.extend({
tableName: 'photos',
imageable: function() {
return this.morphTo('imageable', Site, Post);
}
});</code></pre><p>Optionally, if you wish to use column names other than the <code>name</code> suffixed with <code>_type</code> and <code>_id</code> (for example, if you use a different naming convention in your database), you may specify custom <code>columnNames</code>. This argument, when specified, expects an array containing the substitute <code>_type</code> and <code>_id</code> columns, respectively.</p>
<p>Note that any custom <code>columnNames</code> must be specified on both ends of the relationship! Examples are provided for each of the polymorphic relationship types individually.</p>
</section>
</article>
</section>
<header>
<h2 id="section-Bookshelf">Bookshelf</h2>
<div class="class-description"><p>The Bookshelf library is initialized by passing an initialized Knex client
instance. The knex documentation provides a number of examples for different
databases.</p></div>
</header>
<article>
<div class="container-overview">
<h3
id="Bookshelf-subsection-construction"
class="subsection-title"
>Construction</h3>
<div class="method no-description">
<h4 id="Bookshelf" class="item-header">
<span class="type-signature"></span>
<span class="signature">
<span class="new">new</span>
<span class="parameters"><span class="name"><a href="#Bookshelf">Bookshelf</a></span><span class="parenthesis">(</span><span class="item-name">knex</span><span class="parenthesis">)</span></span><span class="type-signature"></span>
</span
><a href="docs/src_bookshelf.js.html#line15" class="source-link">source</a></h4>
<div class="attributes">
<h5>Parameters</h5>
<ul class="params">
<li>
<code class="param"><span class="item-name">knex</span></code>
<code class="param-type"><span class="param-type"
><code class="param-type"
>Knex</code
>
</span></code>
<div class="description">
<p>Knex instance.</p>
</div>
</li>
</ul>
<dl class="details">
</dl>
</div>
</div>
</div>
<h3
id="Bookshelf-subsection-members"
class="subsection-title"
>Members</h3>
<div class="method has-description">
<h4 id="Bookshelf-instance-knex" class="item-header">
<span class="type-signature"></span>
<span class="signature">
<span class="member-of"
><span class="class-name"
>bookshelf</span
>.</span><span class="name"><a href="#Bookshelf-instance-knex">knex</a></span><span class="type-signature"> :Knex</span>
</span
><a href="docs/src_bookshelf.js.html#line266" class="source-link">source</a></h4>
<div class="attributes">
<dl class="details">
</dl>
</div>
<div class="item-description">
<p>A reference to the <a href="http://knexjs.org">Knex.js</a> instance being used by Bookshelf.</p>
</div>
</div>
<h3
id="Bookshelf-subsection-methods"
class="subsection-title"
>Methods</h3>
<div class="methods">
<div class="method has-description">
<h4 id="Bookshelf-instance-transaction" class="item-header">
<span class="type-signature"></span>
<span class="signature">
<span class="member-of"
><span class="class-name"
>bookshelf</span
>.</span><span class="parameters"><span class="name"><a href="#Bookshelf-instance-transaction">transaction</a></span><span class="parenthesis">(</span><span class="item-name">transactionCallback</span><span class="parenthesis">)</span></span><span class="type-signature"> → Promise<mixed></span>
</span
><a href="docs/src_bookshelf.js.html#line181" class="source-link">source</a></h4>
<div class="attributes">
<h5>Parameters</h5>
<ul class="params">
<li>
<code class="param"><span class="item-name">transactionCallback</span></code>
<code class="param-type"><span class="param-type"
><code class="param-type"
><a href="#Bookshelf~transactionCallback">Bookshelf~transactionCallback</a></code
>
</span></code>
<div class="description">
<p>Callback containing transaction logic. The callback should return a
promise.</p>
</div>
</li>
</ul>
<dl class="details">
</dl>
<h5>Returns</h5>
<code class="param-type"
>Promise<mixed></code
>
<span class="param-desc">
<p>A promise resolving to the value returned from <a href="#Bookshelf~transactionCallback"><code>transactionCallback</code></a>.</p>
</span>
</div>
<div class="item-description">
<p>An alias to <code><a href="http://knexjs.org/#Transactions">Knex#transaction</a></code>, the <code>transaction</code> object must be passed along in the
options of any relevant Bookshelf calls, to ensure all queries are on the
same connection. The entire transaction block is a promise that will
resolve when the transaction is committed, or fail if the transaction is
rolled back.</p>
<pre class="prettyprint source"><code>var Promise = require('bluebird');
Bookshelf.transaction(function(t) {
return new Library({name: 'Old Books'})
.save(null, {transacting: t})
.tap(function(model) {
return Promise.map([
{title: 'Canterbury Tales'},
{title: 'Moby Dick'},
{title: 'Hamlet'}
], function(info) {
// Some validation could take place here.
return new Book(info).save({'shelf_id': model.id}, {transacting: t});
});
});
}).then(function(library) {
console.log(library.related('books').pluck('title'));
}).catch(function(err) {
console.error(err);
});</code></pre>
</div>
</div>
</div>
<h3 class="subsection-title">Type Definitions</h3>
<div class="method has-description">
<h4 id="Bookshelf~transactionCallback" class="item-header">
<span class="type-signature"></span>
<span class="signature">
<span class="parameters"><span class="name"><a href="#Bookshelf~transactionCallback">transactionCallback</a></span><span class="parenthesis">(</span><span class="item-name">transaction</span><span class="parenthesis">)</span></span><span class="type-signature"> → Promise<mixed></span>
</span
><a href="docs/src_bookshelf.js.html#line227" class="source-link">source</a></h4>
<div class="attributes">
<h5>Parameters</h5>
<ul class="params">
<li>
<code class="param"><span class="item-name">transaction</span></code>
<code class="param-type"><span class="param-type"
><code class="param-type"
>Transaction</code
>
</span></code>
<div class="description">
</div>
</li>
</ul>
<dl class="details">
<dt class="tag-see">See</dt>
<dd class="tag-see">
<ul>
<li><a href="http://knexjs.org/#Transactions">Knex#transaction</a></li>
<li><a href="#Bookshelf-instance-transaction">Bookshelf#transaction</a></li>
</ul>
</dd>
</dl>
<h5>Returns</h5>
<code class="param-type"
>Promise<mixed></code
>
</div>
<div class="item-description">
<p>A transaction block to be provided to <a href="#Bookshelf-instance-transaction"><code>Bookshelf#transaction</code></a>.</p>
</div>
</div>
</article>
</section>
<header>
<h2 id="section-Model">Model</h2>
<div class="class-description"><p>Models are simple objects representing individual database rows, specifying
the tableName and any relations to other models. They can be extended with
any domain-specific methods, which can handle components such as validations,
computed properties, and access control.</p></div>
</header>
<article>
<div class="container-overview">
<h3
id="Model-subsection-construction"
class="subsection-title"
>Construction</h3>
<div class="method has-description">
<h4 id="Model" class="item-header">
<span class="type-signature"></span>
<span class="signature">
<span class="new">new</span>
<span class="parameters"><span class="name"><a href="#Model">Model</a></span><span class="parenthesis">(</span><span class="item-name">attributes</span><span class="comma">, </span><span class="optional-bracket">[</span><span class="item-name">options</span><span class="optional-bracket">]</span><span class="parenthesis">)</span></span><span class="type-signature"></span>
</span
><a href="docs/src_model.js.html#line12" class="source-link">source</a></h4>
<div class="attributes">
<h5>Parameters</h5>
<ul class="params">
<li>
<code class="param"><span class="item-name">attributes</span></code>
<code class="param-type"><span class="param-type"
><code class="param-type"
>Object</code
>
</span></code>
<div class="description">
<p>Initial values for this model's attributes.</p>
</div>
</li>
<li>
<code class="param"><span class="optional-bracket">[</span><span class="item-name">options</span><span class="optional-bracket">]</span></code>
<code class="param-type"><span class="param-type"
><code class="param-type"
>Object</code
>
</span></code>
<div class="description">
<p>Hash of options.</p>
<ul class="params">
<li>
<code class="param"><span class="optional-bracket">[</span><span class="item-name">tableName</span><span class="optional-bracket">]</span></code>
<code class="param-type"><span class="param-type"
><code class="param-type"
>string</code
>
</span></code>
<div class="description">