# Notebooks

Source: https://developers.inkdrop.app/data-access/books

Notebooks are how notes are organized in Inkdrop and are commonly used to separate notes by category, project, or purpose.

## The notebook model

The notebook model contains information about your notebook collections, such as their name, the number of notes they contain, associated parent notebook, creation and modification timestamps, and other related metadata.

### Properties

- **\_id** (string)

  The unique notebook ID which should start with `book:` and the remains are randomly generated string.
- **\_rev** (string)

  This is a CouchDB specific field. The current MVCC-token/revision of this document (mandatory and immutable).
- **createdAt** (number)

  The date time when the notebook was created, represented with Unix timestamps in milliseconds.
- **name** (string)

  The notebook name.
- **parentBookId** (nullable string)

  The ID of the parent notebook.
- **updatedAt** (number)

  The date time when the notebook was last updated, represented with Unix timestamps in milliseconds.

```json title="The notebook object"
{
  "_id": "book:Bk5Ivk0T",
  "_rev": "1-ba9bc6e7e45264bb3d6a8f3c266e9df0",
  "updatedAt": 1475373619554,
  "createdAt": 1475373619554,
  "name": "Ideas",
  "parentBookId": "book:ak5I0k0a"
}
```

---

## The notebook class

The `Book` class is a wrapper class of the notebook, providing various methods for its operations such as loading, validation, saving, and serialization.

### Methods

- **static loadWithId(bookId: string)**

  Loads a notebook by its ID from the local database and returns a new instance of the `Book`.
- **constructor(initialValues: Partial\<Book>)**

  Initializes a new `Book` instance with the given initial values. If no values are provided, it assigns default values.
- **validate()**

  Validates the current notebook instance based on the predefined validation rules. If valid, returns an empty array. If not, returns the list of validation errors.
- **save()**

  Validates and then saves the notebook to the local database. Throws an error if the validation fails or if there's a problem with the saving process.
- **toObject()**

  Converts the notebook instance into a plain JavaScript object.
- **toJson()**

  Serializes the notebook instance into a JSON string.

```js title="Import the class"
const { Book } = require('inkdrop').models
```

```js title="Load a notebook from the database"
const book = await Book.loadWithId('book:9dc6a7a7')
```

```js title="Create a new notebook"
const book = new Book({
  name: 'My Notebook'
})
```

```js title="Change its name"
book.name = 'Updated Notebook'
```

```js title="Save the changes"
await book.save()
```

```js title="Convert the notebook into a plain object"
const object = book.toObject()
```

```js title="Convert the notebook into JSON"
const json = book.toJson()
```

---

## Retrieve a notebook `get(docId, options)`

Retrieve a notebook with the given ID.

### Parameters

- **docId** (string, required)

  The notebook ID
- **options** (object)

  Options. See [PouchDB's documentation](https://pouchdb.com/api.html#fetch_document) for available options.

### Returns

Returns a notebook if a valid notebook ID was provided.

```js
const db = env.localDB
const book = await db.books.get('book:Bk5Ivk0T')
```

```json title="Response"
{
  "_id": "book:Bk5Ivk0T",
  "_rev": "1-ba9bc6e7e45264bb3d6a8f3c266e9df0",
  "updatedAt": 1475373619554,
  "createdAt": 1475373619554,
  "name": "Ideas",
  "parentBookId": "book:ak5I0k0a"
}
```

---

## List all notebooks `all()`

Retrieve a list of your notebooks.

### Parameters

No parameters

### Returns

Returns a list of notebooks.

```js
const db = env.localDB
const list = await db.books.all()
```

```js title="Response"
[
  {
    updatedAt: 1475549348850,
    createdAt: 1475549348850,
    name: 'Inbox',
    parentBookId: null,
    _id: 'book:SkTsOceR',
    _rev: '2-aa25f8bfe83cfcd6910fbb78c8e45eeb'
  },
  ...
]
```

---

## Create a notebook ID `createId(): string`

Creates new notebook ID which is String

### Parameters

No parameters

### Returns

Returns a new notebook ID.

```js
const db = env.localDB
const bookId = await db.books.createId()
```

```json title="Response"
"book:ak0s1ce6"
```

---

## Validate a notebook ID `validateDocId(): boolean`

Tests if the given `docId` is a valid notebook ID

### Parameters

- **docId** (string, required)

  A document ID to validate

### Returns

Returns `true` if valid

```js
const db = env.localDB
const isValid = await db.books.validateDocId('book:ak0s1ce6')
```

```json title="Response"
true
```

---

## Create or update a notebook `put(doc)`

Create a new notebook or update an existing note.
If the notebook already exists, you must specify its revision `_rev`, otherwise a conflict will occur.

### Parameters

- **doc** (object, required)

  A Book data to store

### Returns

It throws an `InvalidDataError` if the given doc was invalid.
The response contains the `id` of the document, the new `rev`, and an `ok` to reassure you that everything is okay.

```js
const db = env.localDB
const result = await db.books.put({
  _id: 'book:9IoGtoCuv',
  updatedAt: 1475549348850,
  createdAt: 1475549348850,
  name: 'New Notebook',
  parentBookId: null
})
```

```json title="Response"
{
  "ok": true,
  "id": "book:9IoGtoCuv",
  "rev": "1-A6157A5EA545C99B00FF904EEF05FD9F"
}
```

---

## Remove a notebook `remove(docId)`

Deletes a notebook with the given notebook ID.

> **Warning:**
>
> This method does not delete notes in the notebook. Use [`db.utils.deleteBook(bookId)`](https://developers.inkdrop.app/utils#delete-a-notebook)

### Parameters

- **docId** (string, required)

  A notebook ID to delete.

### Returns

The response contains the `id` of the document, the new `rev`, and an `ok` to reassure you that everything is okay.

```js
const db = env.localDB
const result = await db.books.remove("book:9IoGtoCuv")
```

```json title="Response"
{
  "ok": true,
  "id": "book:9IoGtoCuv",
  "rev": "2-9af304be281790604d1d8a4b0f4c9adb"
}
```

---

## Count number of notebooks `countAll()`

Counts a number of notebooks in the database.

### Parameters

No parameters.

### Returns

Returns a number of notebooks stored in the database.

```js
const db = env.localDB
const num = await db.books.countAll()
```

```json title="Response"
5
```

---

## Lookup a notebook by name `findWithName(name)`

Retrieves a notebook with the given name.

### Parameters

- **name** (string, required)

  A notebook name to find.

### Returns

Returns a notebook if found, otherwise `null`.

```js
const db = env.localDB
const book = await db.books.findWithName('Inbox')
```

```js title="Response"
{
  updatedAt: 1475549348850,
  createdAt: 1475549348850,
  name: 'Inbox',
  parentBookId: null,
  _id: 'book:SkTsOceR',
  _rev: '2-aa25f8bfe83cfcd6910fbb78c8e45eeb'
}
```
