# Модели в Mongoose

Модель в Mongoose - представление коллекции с MongoDB в вашем коди.

Модель используется для:

* осуществление create/read/update/delete (CRUD) операций с коллекцией&#x20;
* валидация CRUD операций&#x20;
* автоматическая генерация схемы коллекции с вашего кода&#x20;
* и т. д.

Создание модели в Mongoose:

```
// 'users'

const Author = mongoose.model('User', userSchema); // schema from previous slide‌
```

Создание нового документа:

```
async function createAuthor() {
    const author = await Author.create({
        first_name: 'Test',
        last_name: 'Testov',
        email: 'example@email.com',
        age: 20,
    });

    return author;
}
```

Обновление документа/документов по критерию:

```
async function updateAuthor() {
    await Author.updateOne({
        email: 'example@email.com'
    }, {
        $set: { first_name: 'Test update' }
    });
}
```

&#x20;Поиск документа/документов:

```
async function findAuthor() {
    const author = await Author.findOne({ email: 'example@email.com' });
    return author;
}
```

Удаление документа:

```
async function deleteAuthor() {
    await Author.deleteOne({ email: 'example@email.com' });
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://reloaderlev.gitbook.io/russian-goit-node-js-new-program/bazy-dannykh/modeli-v-mongoose.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
