# Tags

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

Tags let you add keywords to notes, making them easier to find and browse when you've got a lot of them. Use tags when a note might apply to more than one category or when you want to filter results in a certain notebook by a keyword.

## The tag model

The tag model contains all the information about your tags, such as their name, associated color, creation and modification timestamps, and any other metadata.

### Properties

- **\_id** (string)

  The unique tag ID which should start with `tag:` and the remains are randomly generated string.
  **Pattern:** `^tag:`
  **Length:** `6..128`
- **\_rev** (string)

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

  The color type of the tag. **One of:** `"default"`, `"red"`, `"orange"`, `"yellow"`, `"olive"`, `"green"`, `"teal"`, `"blue"`, `"violet"`, `"purple"`, `"pink"`, `"brown"`, `"grey"`, `"black"`
- **createdAt** (number)

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

  The name of the tag.
  **Length:** `0..64`
- **updatedAt** (number)

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

```json title="The tag object"
{
  "_id": "tag:tBELDUITs",
  "_rev": "5-caf95ffd831665119f6d4f01113cdab4",
  "color": "green",
  "createdAt": 1482130519215,
  "updatedAt": 1493014639273,
  "name": "Admin"
}
```

---

## The tag class

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

### Methods

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

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

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

  Validates the current tag 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 tag to the local database. Throws an error if the validation fails or if there's a problem with the saving process.
- **toObject()**

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

  Serializes the tag instance into a JSON string.

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

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

```js title="Create a new tag"
const tag = new Tag({
  name: 'My tag'
})
```

```js title="Change its name"
tag.name = 'Updated tag'
```

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

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

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

---

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

Retrieve a tag with the given ID.

### Parameters

- **docId** (string, required)

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

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

### Returns

Returns a tag if a valid tag ID was provided.

```js
const db = env.localDB
const tag = await db.tags.get('tag:tBELDUITs')
```

```json title="Response"
{
  "_id": "tag:tBELDUITs",
  "_rev": "5-caf95ffd831665119f6d4f01113cdab4",
  "color": "green",
  "createdAt": 1482130519215,
  "updatedAt": 1493014639273,
  "name": "Admin"
}
```

---

## List all tags `all()`

Retrieve a list of your tags.

### Parameters

No parameters

### Returns

Returns a list of tags.

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

```js title="Response"
[
  {
    "_id": "tag:tBELDUITs",
    "_rev": "5-caf95ffd831665119f6d4f01113cdab4",
    "color": "green",
    "createdAt": 1482130519215,
    "updatedAt": 1493014639273,
    "name": "Admin"
  },
  ...
]
```

---

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

Creates new tag ID which is String

### Parameters

No parameters

### Returns

Returns a new tag ID.

```js
const db = env.localDB
const tagId = await db.tags.createId()
```

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

---

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

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

### Parameters

- **docId** (string, required)

  A document ID to validate

### Returns

Returns `true` if valid

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

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

---

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

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

### Parameters

- **doc** (object, required)

  A Tag 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.tags.put({
  _id: 'tag:9IoGtoCuv',
  updatedAt: 1475549348850,
  createdAt: 1475549348850,
  name: 'New tag',
  color: 'green'
})
```

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

---

## Remove a tag `remove(docId)`

Deletes a tag with the given tag ID.

> **Warning:**
>
> This method does not de-associate the tag from notes. Use [`db.utils.deleteTag(tagId)`](https://developers.inkdrop.app/utils#delete-a-tag)

### Parameters

- **docId** (string, required)

  A tag 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.tags.remove("tag:9IoGtoCuv")
```

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

---

## Count number of tags `countAll()`

Counts a number of tags in the database.

### Parameters

No parameters.

### Returns

Returns a number of tags stored in the database.

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

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

---

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

Retrieves a tag with the given name.

### Parameters

- **name** (string, required)

  A tag name to find.

### Returns

Returns a tag if found, otherwise `null`.

```js
const db = env.localDB
const tag = await db.tags.findWithName('Videography')
```

```js title="Response"
{
  "name": "Videography",
  "color": "red",
  "updatedAt": 1662946230118,
  "createdAt": 1662946219086,
  "_id": "tag:ZiQET3lID",
  "_rev": "2-23c30db926215b718dae860556277fd5"
}
```
