chore(i18n,curriculum): processed translations - new ukrainian (#44447)
This commit is contained in:
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 587d7fb9367417b2b2512c12
|
||||
title: Пошукові ланцюгові помічники запитів для звуження результатів пошуку
|
||||
challengeType: 2
|
||||
forumTopicId: 301533
|
||||
dashedName: chain-search-query-helpers-to-narrow-search-results
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Якщо ви не передаєте зворотній виклик як останній аргумент до `Model.find()` (або інших пошукових методів), запит не буде виконуватися. Ви можете зберегти запит в змінній для подальшого використання. Цей тип об'єкту дозволяє створювати запит за допомогою ланцюгового синтаксису. Фактичний пошук db виконується, коли ви остаточно з'єднали метод `.exec()`. Ви завжди повинні передати зворотній виклик цьому останньому методу. Існує багато помічників для запитів, тут ми використовуємо найбільш поширені.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Змініть функцію `queryChain`, щоб знайти людей, що люблять їжу, вказану змінною `foodToSearch`. Посортуйте їх за `name`, знизьте кількість результатів до двох документів та приховайте їхній вік. Об'єднайте `.find()`, `.sort()`, `.limit()`, `.select()`, and then `.exec()`. Передайте зворотній виклик `done(err, data)` до `exec()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Використання ланцюгових помічників для запитів має бути успішним
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.ajax({
|
||||
url: getUserInput('url') + '/_api/query-tools',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify([
|
||||
{ name: 'Pablo', age: 26, favoriteFoods: ['burrito', 'hot-dog'] },
|
||||
{ name: 'Bob', age: 23, favoriteFoods: ['pizza', 'nachos'] },
|
||||
{ name: 'Ashley', age: 32, favoriteFoods: ['steak', 'burrito'] },
|
||||
{ name: 'Mario', age: 51, favoriteFoods: ['burrito', 'prosciutto'] }
|
||||
])
|
||||
}).then(
|
||||
(data) => {
|
||||
assert.isArray(data, 'the response should be an Array');
|
||||
assert.equal(
|
||||
data.length,
|
||||
2,
|
||||
'the data array length is not what expected'
|
||||
);
|
||||
assert.notProperty(
|
||||
data[0],
|
||||
'age',
|
||||
'The returned first item has too many properties'
|
||||
);
|
||||
assert.equal(
|
||||
data[0].name,
|
||||
'Ashley',
|
||||
'The returned first item name is not what expected'
|
||||
);
|
||||
assert.notProperty(
|
||||
data[1],
|
||||
'age',
|
||||
'The returned second item has too many properties'
|
||||
);
|
||||
assert.equal(
|
||||
data[1].name,
|
||||
'Mario',
|
||||
'The returned second item name is not what expected'
|
||||
);
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 587d7fb6367417b2b2512c07
|
||||
title: Створити модель
|
||||
challengeType: 2
|
||||
forumTopicId: 301535
|
||||
dashedName: create-a-model
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
**C**RUD Частина І - Створення
|
||||
|
||||
Перш за все, вам необхідна схема. Кожна схема пов'язана з колекцією MongoDB. Вона визначає форму документів у цій колекції. Схеми - це блоки, які складають моделі. Вони можуть бути вкладеними для того, щоб створити складні моделі, але в цьому випадку ми не будемо все ускладнювати. Модель дозволяє створювати екземпляри ваших об’єктів, які називаються документами.
|
||||
|
||||
Replit - це справжній сервер, і на реальних серверах взаємодії з базою даних відбуваються у функціях обробника. Ці функції виконуються, коли трапляється якась подія (наприклад, хтось попадає на кінцеву точку вашого API). Ми будемо дотримуватись того самого підходу в цих вправах. Функція `done()` - це зворотний виклик, який повідомляє нас про те, що ми можемо продовжувати після завершення асинхронної операції, такої як вставка, оновлення чи видалення. Він відповідає конвенції Node і повинен називатися `done(null, data)` on success, or `done(err)` в разі помилки.
|
||||
|
||||
Увага! Помилки можуть виникнути при взаємодії з віддаленими службами!
|
||||
|
||||
```js
|
||||
/* Example */
|
||||
|
||||
const someFunc = function(done) {
|
||||
//... do something (risky) ...
|
||||
if (error) return done(error);
|
||||
done(null, result);
|
||||
};
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Створіть особисту схему під назвою `personSchema`, яка має такий прототип:
|
||||
|
||||
```markup
|
||||
- Person Prototype -
|
||||
--------------------
|
||||
name : string [required]
|
||||
age : number
|
||||
favoriteFoods : array of strings (*)
|
||||
```
|
||||
|
||||
Використовуйте основні типи схем Mongoose. Якщо ви хочете, то також можете додати більше полів, використовувати прості валідатори, такі як обов’язкові або унікальні, і встановити значення за замовчуванням. Перегляньте [Mongoose docs](http://mongoosejs.com/docs/guide.html).
|
||||
|
||||
Тепер створіть модель під назвою `Person` from the `personSchema`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Створення екземпляру зі схеми Mongoose повинно пройти успішно
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.post(getUserInput('url') + '/_api/mongoose-model', {
|
||||
name: 'Mike',
|
||||
age: 28,
|
||||
favoriteFoods: ['pizza', 'cheese']
|
||||
}).then(
|
||||
(data) => {
|
||||
assert.equal(data.name, 'Mike', '"model.name" is not what expected');
|
||||
assert.equal(data.age, '28', '"model.age" is not what expected');
|
||||
assert.isArray(
|
||||
data.favoriteFoods,
|
||||
'"model.favoriteFoods" is not an Array'
|
||||
);
|
||||
assert.include(
|
||||
data.favoriteFoods,
|
||||
'pizza',
|
||||
'"model.favoriteFoods" does not include the expected items'
|
||||
);
|
||||
assert.include(
|
||||
data.favoriteFoods,
|
||||
'cheese',
|
||||
'"model.favoriteFoods" does not include the expected items'
|
||||
);
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,56 @@
|
||||
---
|
||||
id: 587d7fb6367417b2b2512c09
|
||||
title: Створіть та збережіть запис моделі
|
||||
challengeType: 2
|
||||
forumTopicId: 301536
|
||||
dashedName: create-and-save-a-record-of-a-model
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
У цьому завданні вам буде потрібно створити та зберегти запис моделі.
|
||||
|
||||
# --instructions--
|
||||
|
||||
У межах функції `createAndSavePerson`, створіть екземпляр документа, використовуючи модель конструктора `Person`, який ви побудували раніше. Перенесіть до конструктора об'єкт, який має поля `name`, `age`, і `favoriteFoods`. Їх типи повинні збігатися з тими, що у `personSchema`. Опісля викличте метод `document.save()` у зворотньому екземплярі документа. Додайте до нього функцію зворотнього виклику використовуючи метод вузла. Це - загальний шаблон; всі такі CRUD-методи потребують функції зворотнього зв'язку в якості останнього аргументу.
|
||||
|
||||
```js
|
||||
/* Example */
|
||||
|
||||
// ...
|
||||
person.save(function(err, data) {
|
||||
// ...do your stuff here...
|
||||
});
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
Створення та збереження елемента БД має пройти успішно
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/create-and-save-person').then(
|
||||
(data) => {
|
||||
assert.isString(data.name, '"item.name" should be a String');
|
||||
assert.isNumber(data.age, '28', '"item.age" should be a Number');
|
||||
assert.isArray(
|
||||
data.favoriteFoods,
|
||||
'"item.favoriteFoods" should be an Array'
|
||||
);
|
||||
assert.equal(data.__v, 0, 'The db item should be not previously edited');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,68 @@
|
||||
---
|
||||
id: 587d7fb7367417b2b2512c0a
|
||||
title: Створюємо багато записів використовуючи model.create()
|
||||
challengeType: 2
|
||||
forumTopicId: 301537
|
||||
dashedName: create-many-records-with-model-create
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Часом потрібно створити багато екземплярів ваших моделей, наприклад, під час заповнення бази даних початковими даними. `Model.create()` приймає масив об'єктів, таких як `[{name: 'John', ...}, {...}, ...]` в якості першого аргумента, і зберігає їх всіх до Бд.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Перейменуйте функцію `createManyPeople` щоб створити багато людей, використовуючи `Model.create()` з аргументом `arrayOfPeople`.
|
||||
|
||||
**Note** Ви можете повторно використати модель встановлену в попередній вправі.
|
||||
|
||||
# --hints--
|
||||
|
||||
Створення одразу багатьох елементів БД має пройти успішно
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.ajax({
|
||||
url: getUserInput('url') + '/_api/create-many-people',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify([
|
||||
{ name: 'John', age: 24, favoriteFoods: ['pizza', 'salad'] },
|
||||
{ name: 'Mary', age: 21, favoriteFoods: ['onions', 'chicken'] }
|
||||
])
|
||||
}).then(
|
||||
(data) => {
|
||||
assert.isArray(data, 'the response should be an array');
|
||||
assert.equal(
|
||||
data.length,
|
||||
2,
|
||||
'the response does not contain the expected number of items'
|
||||
);
|
||||
assert.equal(data[0].name, 'John', 'The first item is not correct');
|
||||
assert.equal(
|
||||
data[0].__v,
|
||||
0,
|
||||
'The first item should be not previously edited'
|
||||
);
|
||||
assert.equal(data[1].name, 'Mary', 'The second item is not correct');
|
||||
assert.equal(
|
||||
data[1].__v,
|
||||
0,
|
||||
'The second item should be not previously edited'
|
||||
);
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,57 @@
|
||||
---
|
||||
id: 587d7fb8367417b2b2512c11
|
||||
title: Видалення багатьох елементів за допомогою model.remove()
|
||||
challengeType: 2
|
||||
forumTopicId: 301538
|
||||
dashedName: delete-many-documents-with-model-remove
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`Model.remove()` корисний для видалення всіх документів, що відповідають заданим критеріям.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Змініть функцію `removeManyPeople`, щоб видалити всіх людей, ім'я яких знаходиться в змінній `nameToRemove`, за допомогою `Model.remove()`. Передайте його до документа запиту з набором полів `name`, і зворотнім викликом.
|
||||
|
||||
**Примітка:** `Model.remove()` не повертає видалений документ, а об'єкт JSON, що містить результат операції та кількість елементів, що постраждали. Не забудьте передати його до зворотного виклику `done()`, оскільки він буде використовуватися у тестах.
|
||||
|
||||
# --hints--
|
||||
|
||||
Видалення одразу декількох елементів має пройти успішно
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.ajax({
|
||||
url: getUserInput('url') + '/_api/remove-many-people',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify([
|
||||
{ name: 'Mary', age: 16, favoriteFoods: ['lollipop'] },
|
||||
{ name: 'Mary', age: 21, favoriteFoods: ['steak'] }
|
||||
])
|
||||
}).then(
|
||||
(data) => {
|
||||
assert.isTrue(!!data.ok, 'The mongo stats are not what expected');
|
||||
assert.equal(
|
||||
data.n,
|
||||
2,
|
||||
'The number of items affected is not what expected'
|
||||
);
|
||||
assert.equal(data.count, 0, 'the db items count is not what expected');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,53 @@
|
||||
---
|
||||
id: 587d7fb8367417b2b2512c10
|
||||
title: Видалення одного документа за допомогою model.findByIdAndRemove
|
||||
challengeType: 2
|
||||
forumTopicId: 301539
|
||||
dashedName: delete-one-document-using-model-findbyidandremove
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`findByIdAndRemove` і `findOneAndRemove` схожі до попередніх методів оновлення. Вони передають вилучений документ до db. Використовуйте аргумент функції `personId` як ключ пошуку.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Змініть функцію `removeById`, щоб видалити одну особу на основі її `_id`. Потрібно використовувати один із методів `findByIdAndRemove()` or `findOneAndRemove()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Видалення елемента має бути успішним
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.post(getUserInput('url') + '/_api/remove-one-person', {
|
||||
name: 'Jason Bourne',
|
||||
age: 36,
|
||||
favoriteFoods: ['apples']
|
||||
}).then(
|
||||
(data) => {
|
||||
assert.equal(data.name, 'Jason Bourne', 'item.name is not what expected');
|
||||
assert.equal(data.age, 36, 'item.age is not what expected');
|
||||
assert.deepEqual(
|
||||
data.favoriteFoods,
|
||||
['apples'],
|
||||
'item.favoriteFoods is not what expected'
|
||||
);
|
||||
assert.equal(data.__v, 0);
|
||||
assert.equal(data.count, 0, 'the db items count is not what expected');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,85 @@
|
||||
---
|
||||
id: 587d7fb6367417b2b2512c06
|
||||
title: Встановлення і налаштування Mongoose
|
||||
challengeType: 2
|
||||
forumTopicId: 301540
|
||||
dashedName: install-and-set-up-mongoose
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Робота над цими завданнями включатиме написання вашого коду з використанням одного з наступних методів:
|
||||
|
||||
- Створіть [цей GitHub репозитарій](https://github.com/freeCodeCamp/boilerplate-mongomongoose/) і локально завершіть ці завдання.
|
||||
- Використовуйте [наш стартовий проєкт Replit](https://replit.com/github/freeCodeCamp/boilerplate-mongomongoose) для виконання цих завдань.
|
||||
- Використовуйте конструктор сайту на власний розсуд, щоб завершити проєкт. Перевірте, що ви зберегли усі файли з нашого репозиторію GitHub.
|
||||
|
||||
По завершенню, переконайтеся, що працююча демоверсія вашого проєкту розміщена у відкритому доступі. Потім введіть URL - адресу проєкту в поле `Solution Link` field.
|
||||
|
||||
У цьому завданні, створіть базу даних MongoDB Atlas та імпортуйте необхідні пакети для підключення до неї.
|
||||
|
||||
Дотримуйтесь <a href='https://www.freecodecamp.org/news/get-started-with-mongodb-atlas/' rel='noopener noreferrer' target='_blank'>цих вказівок</a>, щоб налаштувати розміщену базу даних на MongoDB Atlas.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Додайте `mongodb@~3.6.0` і `mongoose@~5.4.0` до `package.json` проєкту. Потім, необхідно встановити mongoose як `mongoose` у `myApp.js`. Створіть файл `.env` і додайте до нього змінну `MONGO_URI`. Його значенням має бути ваш URI бази даних MongoDB Atlas. Обов'язково помістіть URI в одинарні чи подвійні лапки, і пам'ятайте, що ви не можете використовувати пробіли навколо `=` у змінних середовища. Наприклад, `MONGO_URI='VALUE'`. Після завершення, під'єднайтесь до бази даних, використовуючи наступний синтаксис:
|
||||
|
||||
```js
|
||||
mongoose.connect(<Your URI>, { useNewUrlParser: true, useUnifiedTopology: true });
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
Залежність "mongodb" слід вказати в package.json
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/file/package.json').then(
|
||||
(data) => {
|
||||
var packJson = JSON.parse(data);
|
||||
assert.property(packJson.dependencies, 'mongodb');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
Залежність "mongoose" слід вказати в package.json
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/file/package.json').then(
|
||||
(data) => {
|
||||
var packJson = JSON.parse(data);
|
||||
assert.property(packJson.dependencies, 'mongoose');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
"mongoose" слід підключити до бази даних
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/is-mongoose-ok').then(
|
||||
(data) => {
|
||||
assert.isTrue(data.isMongooseOk, 'mongoose is not connected');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,54 @@
|
||||
---
|
||||
id: 587d7fb8367417b2b2512c0e
|
||||
title: 'Виконайте класичні оновлення здійснюючи пошук, редагування і збереження'
|
||||
challengeType: 2
|
||||
forumTopicId: 301541
|
||||
dashedName: perform-classic-updates-by-running-find-edit-then-save
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
У старі добрі часи це було те, що вам потрібно було робити, якщо ви хотіли відредагувати документ і мати можливість якимсь чином ним користуватися (наприклад, надіслати його назад у відповіді сервера). Mongoose має спеціальний метод оновлення: `Model.update()`. Він прив'язаний до драйвера з низьким рівнем монго. Він може редагувати багато документів, що відповідають певним критеріям, але не надсилає оновлений документ, а лише повідомлення про статус. Крім того, це ускладнює перевірку моделі, оскільки просто викликає безпосередньо драйвер mongo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Змініть функцію `findEditThenSave`, щоб знайти особу за `_id` (використовуйте будь - який із вищезгаданих методів) з параметром `personId` як ключ пошуку. Додайте `"hamburger"` до списку `favoriteFoods` людини (можна використовувати `Array.push()`). Потім всередині зворотного виклику пошуку - `save()` оновлений`Person`.
|
||||
|
||||
**Примітка:** Це може бути складно, якщо у вашій схемі, ви визначили `favoriteFoods` як масив, не вказуючи тип (тобто `[String]`). В такому випадку `favoriteFoods` за замовчуванням приймає змішаний тип, і вам потрібно вручну позначити його як відредагований за допомогою `document.markModified('edited-field')`. Перегляньте [Mongoose documentation](https://mongoosejs.com/docs/schematypes.html#Mixed)
|
||||
|
||||
# --hints--
|
||||
|
||||
Пошук-редагування-оновлення елемента має бути успішним
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.post(getUserInput('url') + '/_api/find-edit-save', {
|
||||
name: 'Poldo',
|
||||
age: 40,
|
||||
favoriteFoods: ['spaghetti']
|
||||
}).then(
|
||||
(data) => {
|
||||
assert.equal(data.name, 'Poldo', 'item.name is not what is expected');
|
||||
assert.equal(data.age, 40, 'item.age is not what expected');
|
||||
assert.deepEqual(
|
||||
data.favoriteFoods,
|
||||
['spaghetti', 'hamburger'],
|
||||
'item.favoriteFoods is not what expected'
|
||||
);
|
||||
assert.equal(data.__v, 1, 'The item should be previously edited');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,58 @@
|
||||
---
|
||||
id: 587d7fb8367417b2b2512c0f
|
||||
title: Виконання нових оновлень для документа за допомогою model.findOneAndUpdate()
|
||||
challengeType: 2
|
||||
forumTopicId: 301542
|
||||
dashedName: perform-new-updates-on-a-document-using-model-findoneandupdate
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Останні версії Mongoose мають методи спрощення оновлення документів. Деякі більш розширені функції (наприклад, хуки до/після, перевірка) поводяться з таким підходом по-різному, тому класичний метод все ще корисний у багатьох ситуаціях. `findByIdAndUpdate()` можна використовувати під час пошуку за id.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Змініть функцію `findAndUpdate`, щоб знайти особу за `Name` і встановити вік особи за `20`. Використовуйте параметр функції `personName` як ключ пошуку.
|
||||
|
||||
**Примітка:** Ви повинні повернути оновлений документ. Для цього необхідно передати опції документа `{ new: true }` як третій аргумент `findOneAndUpdate()`. За замовчуванням ці методи повертають немодифікований об'єкт.
|
||||
|
||||
# --hints--
|
||||
|
||||
пошук OneAndUpdate елемента має бути успішним
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.post(getUserInput('url') + '/_api/find-one-update', {
|
||||
name: 'Dorian Gray',
|
||||
age: 35,
|
||||
favoriteFoods: ['unknown']
|
||||
}).then(
|
||||
(data) => {
|
||||
assert.equal(data.name, 'Dorian Gray', 'item.name is not what expected');
|
||||
assert.equal(data.age, 20, 'item.age is not what expected');
|
||||
assert.deepEqual(
|
||||
data.favoriteFoods,
|
||||
['unknown'],
|
||||
'item.favoriteFoods is not what expected'
|
||||
);
|
||||
assert.equal(
|
||||
data.__v,
|
||||
0,
|
||||
'findOneAndUpdate does not increment version by design!'
|
||||
);
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,53 @@
|
||||
---
|
||||
id: 587d7fb7367417b2b2512c0b
|
||||
title: Використання model.find() для пошуку вашої бази даних
|
||||
challengeType: 2
|
||||
forumTopicId: 301543
|
||||
dashedName: use-model-find-to-search-your-database
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
У найпростішому використанні, `Model.find()` приймає документ - запит ( об'єкт JSON) як перший аргумент, а потім - зворотній виклик. Це повертає масив збігів. Це підтримує надзвичайно широкий спектр варіантів пошуку. Читайте більше в документації.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Змініть функцію `findPeopleByName`, щоб знайти всіх людей з даним іменем, використовуючи <code>Model.find() -\> [Person]</code>
|
||||
|
||||
Використовуйте аргумент функції `personName` як ключ пошуку.
|
||||
|
||||
# --hints--
|
||||
|
||||
Пошук усіх елементів, що відповідають критеріям, мають бути успішними
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.post(getUserInput('url') + '/_api/find-all-by-name', {
|
||||
name: 'r@nd0mN4m3',
|
||||
age: 24,
|
||||
favoriteFoods: ['pizza']
|
||||
}).then(
|
||||
(data) => {
|
||||
assert.isArray(data, 'the response should be an Array');
|
||||
assert.equal(
|
||||
data[0].name,
|
||||
'r@nd0mN4m3',
|
||||
'item.name is not what expected'
|
||||
);
|
||||
assert.equal(data[0].__v, 0, 'The item should be not previously edited');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,48 @@
|
||||
---
|
||||
id: 587d7fb7367417b2b2512c0d
|
||||
title: Використання model.findById() для пошуку вашої бази даних за допомогою _id
|
||||
challengeType: 2
|
||||
forumTopicId: 301544
|
||||
dashedName: use-model-findbyid-to-search-your-database-by-id
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
При збереженні документу, MongoDB автоматично додає поле `_id`, і встановлює для нього унікальний алфавітно-цифровий ключ. Пошук за `_id` є надзвичайно частою операцією, тому Mongoose надає для цього спеціалізований метод.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Змініть `findPersonById`, щоб знайти лише одну особу, яка має заданий `_id`, використовуючи `Model.findById() -> Person`. Використовуйте аргумент функції `personId` як ключ пошуку.
|
||||
|
||||
# --hints--
|
||||
|
||||
Пошук елемента за Id має бути успішним
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/find-by-id').then(
|
||||
(data) => {
|
||||
assert.equal(data.name, 'test', 'item.name is not what expected');
|
||||
assert.equal(data.age, 0, 'item.age is not what expected');
|
||||
assert.deepEqual(
|
||||
data.favoriteFoods,
|
||||
['none'],
|
||||
'item.favoriteFoods is not what expected'
|
||||
);
|
||||
assert.equal(data.__v, 0, 'The item should be not previously edited');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
@ -0,0 +1,51 @@
|
||||
---
|
||||
id: 587d7fb7367417b2b2512c0c
|
||||
title: Використання model.findOne() для повернення єдиного відповідного документа з вашої бази даних
|
||||
challengeType: 2
|
||||
forumTopicId: 301545
|
||||
dashedName: use-model-findone-to-return-a-single-matching-document-from-your-database
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
`Model.findOne()` функціонує як `Model.find()`, але повертає лише один документ (не масив), навіть якщо є кілька елементів. Це особливо корисно під час пошуку за властивостями, які були оголошені як унікальні.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Змініть функцію `findOneByFood`, щоб знайти лише одну особу, яка має певну їжу у своїх вподобаннях, використовуючи модель `Model.findOne() -> Person`. Використовуйте аргумент функції `food` як ключ пошуку.
|
||||
|
||||
# --hints--
|
||||
|
||||
Пошук елемента має бути успішним
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.post(getUserInput('url') + '/_api/find-one-by-food', {
|
||||
name: 'Gary',
|
||||
age: 46,
|
||||
favoriteFoods: ['chicken salad']
|
||||
}).then(
|
||||
(data) => {
|
||||
assert.equal(data.name, 'Gary', 'item.name is not what expected');
|
||||
assert.deepEqual(
|
||||
data.favoriteFoods,
|
||||
['chicken salad'],
|
||||
'item.favoriteFoods is not what expected'
|
||||
);
|
||||
assert.equal(data.__v, 0, 'The item should be not previously edited');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
/**
|
||||
Backend challenges don't need solutions,
|
||||
because they would need to be tested against a full working project.
|
||||
Please check our contributing guidelines to learn more.
|
||||
*/
|
||||
```
|
Reference in New Issue
Block a user