fix(curriculum): fix challenges for russian language
This commit is contained in:
@@ -1,19 +1,20 @@
|
||||
---
|
||||
id: 587d7fb9367417b2b2512c12
|
||||
title: Chain Search Query Helpers to Narrow Search Results
|
||||
localeTitle: Помощники поискового запроса цепочки сужают результаты поиска
|
||||
challengeType: 2
|
||||
forumTopicId: 301533
|
||||
localeTitle: Помощники поискового запроса цепочки сужают результаты поиска
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<section id='description'>
|
||||
Если вы не передадите обратный вызов в качестве последнего аргумента для Model.find () (или для других методов поиска), запрос не будет выполнен. Вы можете сохранить запрос в переменной для дальнейшего использования. Этот тип объекта позволяет создавать запрос с использованием синтаксиса цепочки. Фактический поиск в БД выполняется, когда вы, наконец, связываете метод .exec (). Передайте обратный вызов этому последнему методу. Есть много помощников запросов, здесь мы будем использовать самые «известные».
|
||||
Найди людей которые любят «буррито». Сортируйте их по имени, ограничьте результаты двумя документами и скройте их возраст. Цепочка .find (), .sort (), .limit (), .select (), а затем .exec (). Передайте обратный вызов done (err, data) в exec ().
|
||||
Найди людей которые любят «буррито». Сортируйте их по имени, ограничьте результаты двумя документами и скройте их возраст. Цепочка .find (), .sort (), .limit (), .select (), а затем .exec (). Передайте обратный вызов done (err, data) в exec ().
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
<section id='instructions'>
|
||||
Find people who like <code>burrito</code>. Sort them by name, limit the results to two documents, and hide their age. Chain <code>.find()</code>, <code>.sort()</code>, <code>.limit()</code>, <code>.select()</code>, and then <code>.exec()</code>. Pass the <code>done(err, data)</code> callback to <code>exec()</code>.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
@@ -21,22 +22,9 @@ challengeType: 2
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Помощники цепочки запросов должны быть успешными
|
||||
- text: Chaining query helpers should succeed
|
||||
testString: '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); })'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -1,12 +1,13 @@
|
||||
---
|
||||
id: 587d7fb6367417b2b2512c07
|
||||
title: Create a Model
|
||||
localeTitle: Создать модель
|
||||
challengeType: 2
|
||||
forumTopicId: 301535
|
||||
localeTitle: Создать модель
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<section id='description'>
|
||||
Прежде всего нам нужна схема. Каждая схема отображается в коллекцию MongoDB. Он определяет форму документов в этой коллекции.
|
||||
Схемы являются строительным блоком для Моделей. Они могут быть вложенными для создания сложных моделей, но в этом случае мы будем делать все просто.
|
||||
Модель позволяет создавать экземпляры ваших объектов, называемые документами.
|
||||
@@ -27,12 +28,23 @@ challengeType: 2
|
||||
<code>//... do something (risky) ...</code>
|
||||
<code>if(error) return done(error);</code>
|
||||
<code>done(null, result);</code>
|
||||
<code>};</code>
|
||||
<code>};</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
<section id='instructions'>
|
||||
Create a person having this prototype :
|
||||
<blockquote>
|
||||
- Person Prototype -<br>
|
||||
--------------------<br>
|
||||
name : string [required]<br>
|
||||
age : number<br>
|
||||
favoriteFoods : array of strings (*)
|
||||
</blockquote>
|
||||
|
||||
Use the mongoose basic schema types. If you want you can also add
|
||||
more fields, use simple validators like required or unique,
|
||||
and set default values. See the <a href='http://mongoosejs.com/docs/guide.html'>mongoose docs</a>.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
@@ -40,22 +52,9 @@ challengeType: 2
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Создание экземпляра из схемы мангуста должно завершиться успешно
|
||||
- text: Creating an instance from a mongoose schema should succeed
|
||||
testString: '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); })'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -1,22 +1,33 @@
|
||||
---
|
||||
id: 587d7fb6367417b2b2512c09
|
||||
title: Create and Save a Record of a Model
|
||||
localeTitle: Создать и сохранить запись модели
|
||||
challengeType: 2
|
||||
forumTopicId: 301536
|
||||
localeTitle: Создать и сохранить запись модели
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Создайте экземпляр документа с помощью созданного ранее конструктора Person. Передайте в конструктор объект с полями name, age и FavoritesFoods. Их типы должны соответствовать типам в схеме Person. Затем вызовите метод document.save () для возвращенного экземпляра документа. Передайте ему обратный вызов, используя соглашение Node. Это общий шаблон, все последующие методы CRUD принимают функцию обратного вызова, подобную этой, в качестве последнего аргумента.
|
||||
<code>/* Example */</code>
|
||||
<code>// ...</code>
|
||||
<code>person.save(function(err, data) {</code>
|
||||
<code>// ...do your stuff here...</code>
|
||||
<code>});</code>
|
||||
<section id='description'>
|
||||
Создайте экземпляр документа с помощью созданного ранее конструктора Person. Передайте в конструктор объект с полями name, age и FavoritesFoods. Их типы должны соответствовать типам в схеме Person. Затем вызовите метод document.save () для возвращенного экземпляра документа. Передайте ему обратный вызов, используя соглашение Node. Это общий шаблон, все последующие методы CRUD принимают функцию обратного вызова, подобную этой, в качестве последнего аргумента.
|
||||
<code>/* Example */</code>
|
||||
<code>// ...</code>
|
||||
<code>person.save(function(err, data) {</code>
|
||||
<code>// ...do your stuff here...</code>
|
||||
<code>});</code>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
<section id='instructions'>
|
||||
Create a document instance using the <code>Person</code> constructor you built before. Pass to the constructor an object having the fields <code>name</code>, <code>age</code>, and <code>favoriteFoods</code>. Their types must conform to the ones in the Person Schema. Then call the method <code>document.save()</code> on the returned document instance. Pass to it a callback using the Node convention. This is a common pattern, all the following CRUD methods take a callback function like this as the last argument.
|
||||
|
||||
```js
|
||||
/* Example */
|
||||
|
||||
// ...
|
||||
person.save(function(err, data) {
|
||||
// ...do your stuff here...
|
||||
});
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
@@ -25,22 +36,9 @@ challengeType: 2
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Создание и сохранение элемента БД должно завершиться успешно
|
||||
testString: '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); })'
|
||||
- text: Creating and saving a db item should succeed
|
||||
testString: 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); })
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -1,18 +1,19 @@
|
||||
---
|
||||
id: 587d7fb7367417b2b2512c0a
|
||||
title: Create Many Records with model.create()
|
||||
localeTitle: Создать много записей с model.create ()
|
||||
challengeType: 2
|
||||
forumTopicId: 301537
|
||||
localeTitle: Создать много записей с model.create ()
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Иногда вам нужно создать множество экземпляров ваших моделей, например, при заполнении базы данных исходными данными. Model.create () принимает массив объектов, таких как [{name: 'John', ...}, {...}, ...], в качестве первого аргумента и сохраняет их все в БД. Создайте много людей с Model.create (), используя аргумент функции arrayOfPeople.
|
||||
<section id='description'>
|
||||
Иногда вам нужно создать множество экземпляров ваших моделей, например, при заполнении базы данных исходными данными. Model.create () принимает массив объектов, таких как [{name: 'John', ...}, {...}, ...], в качестве первого аргумента и сохраняет их все в БД. Создайте много людей с Model.create (), используя аргумент функции arrayOfPeople.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
<section id='instructions'>
|
||||
Create many people with <code>Model.create()</code>, using the function argument <code>arrayOfPeople</code>.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
@@ -20,22 +21,9 @@ challengeType: 2
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Создание нескольких элементов БД одновременно должно быть успешным
|
||||
- text: Creating many db items at once should succeed
|
||||
testString: '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); })'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -1,19 +1,21 @@
|
||||
---
|
||||
id: 587d7fb8367417b2b2512c11
|
||||
title: Delete Many Documents with model.remove()
|
||||
localeTitle: Удалить много документов с model.remove ()
|
||||
challengeType: 2
|
||||
forumTopicId: 301538
|
||||
localeTitle: Удалить много документов с model.remove ()
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<section id='description'>
|
||||
Model.remove () полезна для удаления всех документов, соответствующих заданным критериям. Удалите всех людей с именем «Мэри», используя Model.remove (). Передайте его в документ запроса с установленным полем «имя» и, конечно, с обратным вызовом.
|
||||
Примечание: Model.remove () возвращает не удаленный документ, а объект JSON, содержащий результат операции и количество затронутых элементов. Не забудьте передать его обратному вызову done (), так как мы используем его в тестах.
|
||||
Примечание: Model.remove () возвращает не удаленный документ, а объект JSON, содержащий результат операции и количество затронутых элементов. Не забудьте передать его обратному вызову done (), так как мы используем его в тестах.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
<section id='instructions'>
|
||||
Delete all the people whose name is “Mary”, using <code>Model.remove()</code>. Pass it to a query document with the <code>name</code> field set, and of course a callback.
|
||||
<strong>Note:</strong> The <code>Model.remove()</code> doesn’t return the deleted document, but a JSON object containing the outcome of the operation, and the number of items affected. Don’t forget to pass it to the <code>done()</code> callback, since we use it in tests.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
@@ -21,22 +23,9 @@ Model.remove () полезна для удаления всех документ
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Удаление сразу нескольких элементов должно завершиться успешно
|
||||
- text: Deleting many items at once should succeed
|
||||
testString: '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); })'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -1,17 +1,18 @@
|
||||
---
|
||||
id: 587d7fb8367417b2b2512c10
|
||||
title: Delete One Document Using model.findByIdAndRemove
|
||||
localeTitle: Удалить один документ с помощью model.findByIdAndRemove
|
||||
challengeType: 2
|
||||
forumTopicId: 301539
|
||||
localeTitle: Удалить один документ с помощью model.findByIdAndRemove
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Удалить одного человека по ее _id. Вы должны использовать один из методов findByIdAndRemove () или findOneAndRemove (). Они похожи на предыдущие методы обновления. Они передают удаленный документ в cb. Как обычно, используйте аргумент функции personId в качестве ключа поиска.
|
||||
<section id='description'>
|
||||
Удалить одного человека по ее _id. Вы должны использовать один из методов findByIdAndRemove () или findOneAndRemove (). Они похожи на предыдущие методы обновления. Они передают удаленный документ в cb. Как обычно, используйте аргумент функции personId в качестве ключа поиска.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
@@ -20,22 +21,9 @@ challengeType: 2
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Удаление элемента должно завершиться успешно
|
||||
- text: Deleting an item should succeed
|
||||
testString: '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); })'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -1,18 +1,21 @@
|
||||
---
|
||||
id: 587d7fb6367417b2b2512c06
|
||||
title: Install and Set Up Mongoose
|
||||
localeTitle: Установить и настроить Mongoose
|
||||
challengeType: 2
|
||||
forumTopicId: 301540
|
||||
localeTitle: Установить и настроить Mongoose
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Добавьте mongodb и mongoose в пакет проекта.json. Тогда требуй мангуста. Сохраните свой URI базы данных mLab в личном файле .env как MONGO_URI. Подключитесь к базе данных, используя mongoose.connect ( <Your URI> )
|
||||
<section id='description'>
|
||||
Добавьте mongodb и mongoose в пакет проекта.json. Тогда требуй мангуста. Сохраните свой URI базы данных mLab в личном файле .env как MONGO_URI. Подключитесь к базе данных, используя mongoose.connect ( <Your URI> )
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
<section id='instructions'>
|
||||
Add mongodb and mongoose to the project’s <code>package.json</code>. Then require mongoose. Store your mLab database URI in the private <code>.env</code> file as <code>MONGO_URI</code>. Connect to the database using <code>mongoose.connect(<Your URI>)</code>
|
||||
|
||||
<section id='instructions'>
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
@@ -20,26 +23,13 @@ challengeType: 2
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Зависимость "mongodb" должна быть в package.json
|
||||
testString: '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); })'
|
||||
- text: Зависимость "mongoose" должна быть в package.json
|
||||
testString: '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); })'
|
||||
- text: «Мангуст» должен быть подключен к базе данных »
|
||||
testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/is-mongoose-ok'').then(data => {assert.isTrue(data.isMongooseOk, ''mongoose is not connected'')}, xhr => { throw new Error(xhr.responseText); })'
|
||||
- text: '"mongodb" dependency should be in package.json'
|
||||
testString: 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); })
|
||||
- text: '"mongoose" dependency should be in package.json'
|
||||
testString: 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); })
|
||||
- text: '"mongoose" should be connected to a database'
|
||||
testString: getUserInput => $.get(getUserInput('url') + '/_api/is-mongoose-ok').then(data => {assert.isTrue(data.isMongooseOk, 'mongoose is not connected')}, xhr => { throw new Error(xhr.responseText); })
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -1,20 +1,23 @@
|
||||
---
|
||||
id: 587d7fb8367417b2b2512c0e
|
||||
title: 'Perform Classic Updates by Running Find, Edit, then Save'
|
||||
localeTitle: «Выполните классические обновления, запустив Find, Edit, затем Save»
|
||||
title: Perform Classic Updates by Running Find, Edit, then Save
|
||||
challengeType: 2
|
||||
forumTopicId: 301541
|
||||
localeTitle: «Выполните классические обновления, запустив Find, Edit, затем Save»
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<section id='description'>
|
||||
В старые добрые времена это было то, что вам нужно было сделать, если вы хотите отредактировать документ и иметь возможность каким-либо образом его использовать, например, отправив его обратно в ответе сервера. У Mongoose есть специальный метод обновления: Model.update (). Он привязан к низкоуровневому драйверу монго. Он может массово редактировать многие документы, соответствующие определенным критериям, но он не отправляет обратно обновленный документ, только сообщение о статусе. Кроме того, это затрудняет проверку модели, потому что она просто вызывает драйвер Монго.
|
||||
Найдите человека по _id (используйте любой из вышеперечисленных методов) с параметром personId в качестве ключа поиска. Добавьте «гамбургер» в список ее любимых продуктов (вы можете использовать Array.push ()). Затем - внутри обратного вызова find - save () обновленный Person.
|
||||
[*] Подсказка: это может быть непросто, если в вашей Схеме вы объявили FavoritesFoods как Массив без указания типа (например, [String]). В этом случае по умолчанию в файле favourFoods используется смешанный тип, и вы должны вручную пометить его как отредактированный с помощью document.markModified ('edited-field'). (http://mongoosejs.com/docs/schematypes.html - # Смешанный)
|
||||
[*] Подсказка: это может быть непросто, если в вашей Схеме вы объявили FavoritesFoods как Массив без указания типа (например, [String]). В этом случае по умолчанию в файле favourFoods используется смешанный тип, и вы должны вручную пометить его как отредактированный с помощью document.markModified ('edited-field'). (http://mongoosejs.com/docs/schematypes.html - # Смешанный)
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
<section id='instructions'>
|
||||
Find a person by <code>\_id</code> ( use any of the above methods ) with the parameter <code>personId</code> as search key. Add "hamburger" to the list of the person's <code>favoriteFoods</code> (you can use <code>Array.push()</code>). Then - inside the find callback - <code>save()</code> the updated <code>Person</code>.
|
||||
|
||||
<strong>Note:</strong> This may be tricky, if in your Schema, you declared <code>favoriteFoods</code> as an Array, without specifying the type (i.e. <code>[String]</code>). In that <code>casefavoriteFoods</code> defaults to Mixed type, and you have to manually mark it as edited using <code>document.markModified('edited-field')</code>. See [Mongoose documentation](https://mongoosejs.com/docs/schematypes.html#Mixed)
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
@@ -22,22 +25,9 @@ challengeType: 2
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Поиск-редактирование-обновление элемента должно завершиться успешно
|
||||
testString: '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 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); })'
|
||||
- text: Find-edit-update an item should succeed
|
||||
testString: '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); })'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -1,20 +1,22 @@
|
||||
---
|
||||
id: 587d7fb8367417b2b2512c0f
|
||||
title: Perform New Updates on a Document Using model.findOneAndUpdate()
|
||||
localeTitle: Выполнять новые обновления в документе с помощью model.findOneAndUpdate ()
|
||||
challengeType: 2
|
||||
forumTopicId: 301542
|
||||
localeTitle: Выполнять новые обновления в документе с помощью model.findOneAndUpdate ()
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<section id='description'>
|
||||
последних версиях mongoose есть методы, упрощающие обновление документов. Некоторые более продвинутые функции (например, до / после перехвата, проверка) ведут себя по-разному с этим подходом, поэтому метод Classic по-прежнему полезен во многих ситуациях. findByIdAndUpdate () может использоваться при поиске по Id.
|
||||
Найдите человека по имени и установите для него возраст 20. Используйте параметр функции personName в качестве ключа поиска.
|
||||
Подсказка: мы хотим, чтобы вы вернули обновленный документ. Для этого вам нужно передать документ параметров {new: true} в качестве 3-го аргумента для findOneAndUpdate (). По умолчанию эти методы возвращают неизмененный объект.
|
||||
Подсказка: мы хотим, чтобы вы вернули обновленный документ. Для этого вам нужно передать документ параметров {new: true} в качестве 3-го аргумента для findOneAndUpdate (). По умолчанию эти методы возвращают неизмененный объект.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
<section id='instructions'>
|
||||
Find a person by <code>Name</code> and set the person's age to 20. Use the function parameter <code>personName</code> as search key.
|
||||
<strong>Note:</strong> You should return the updated document. To do that you need to pass the options document <code>{ new: true }</code> as the 3rd argument to <code>findOneAndUpdate()</code>. By default these methods return the unmodified object.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
@@ -22,22 +24,9 @@ challengeType: 2
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: findOneAndUpdate элемент должен быть успешным
|
||||
- text: findOneAndUpdate an item should succeed
|
||||
testString: '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); })'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -6,13 +6,13 @@ challengeType: 2
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<section id='description'>
|
||||
Найдите всех людей с данным именем, используя Model.find () -> [Person]
|
||||
В простейшем случае Model.find () принимает документ запроса (объект JSON) в качестве первого аргумента, а затем обратный вызов. Возвращает массив совпадений. Он поддерживает чрезвычайно широкий спектр параметров поиска. Проверьте это в документах. Используйте аргумент функции personName в качестве ключа поиска.
|
||||
В простейшем случае Model.find () принимает документ запроса (объект JSON) в качестве первого аргумента, а затем обратный вызов. Возвращает массив совпадений. Он поддерживает чрезвычайно широкий спектр параметров поиска. Проверьте это в документах. Используйте аргумент функции personName в качестве ключа поиска.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
@@ -23,20 +23,6 @@ challengeType: 2
|
||||
tests:
|
||||
- text: Найти все элементы, соответствующие критериям, должны быть успешными
|
||||
testString: '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); })'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -1,18 +1,19 @@
|
||||
---
|
||||
id: 587d7fb7367417b2b2512c0d
|
||||
title: Use model.findById() to Search Your Database By _id
|
||||
localeTitle: Используйте model.findById () для поиска в вашей базе данных по _id
|
||||
challengeType: 2
|
||||
forumTopicId: 301544
|
||||
localeTitle: Используйте model.findById () для поиска в вашей базе данных по _id
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
При сохранении документа mongodb автоматически добавляет поле _id и присваивает ему уникальный буквенно-цифровой ключ. Поиск по _id является чрезвычайно частой операцией, поэтому mongoose предоставляет для нее специальный метод. Найдите (только !!) человека, имеющего данный _id, используя Model.findById () -> Person. Используйте аргумент функции personId в качестве ключа поиска.
|
||||
<section id='description'>
|
||||
При сохранении документа mongodb автоматически добавляет поле _id и присваивает ему уникальный буквенно-цифровой ключ. Поиск по _id является чрезвычайно частой операцией, поэтому mongoose предоставляет для нее специальный метод. Найдите (только !!) человека, имеющего данный _id, используя Model.findById () -> Person. Используйте аргумент функции personId в качестве ключа поиска.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
<section id='instructions'>
|
||||
Find the (only!!) person having a given <code>_id</code>, using <code>Model.findById() -> Person</code>. Use the function argument <code>personId</code> as the search key.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
@@ -20,22 +21,9 @@ challengeType: 2
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Найти предмет по идентификатору должно получиться
|
||||
testString: '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); })'
|
||||
- text: Find an item by Id should succeed
|
||||
testString: 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); })
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
@@ -1,18 +1,19 @@
|
||||
---
|
||||
id: 587d7fb7367417b2b2512c0c
|
||||
title: Use model.findOne() to Return a Single Matching Document from Your Database
|
||||
localeTitle: Используйте model.findOne (), чтобы вернуть один соответствующий документ из вашей базы данных
|
||||
challengeType: 2
|
||||
forumTopicId: 301545
|
||||
localeTitle: Используйте model.findOne (), чтобы вернуть один соответствующий документ из вашей базы данных
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Model.findOne () ведет себя как .find (), но возвращает только один документ (не массив), даже если есть несколько элементов. Это особенно полезно при поиске по свойствам, которые вы объявили уникальными. Найдите только одного человека, у которого есть определенная еда в избранном, используя Model.findOne () -> Person. Используйте аргумент функции food в качестве ключа поиска.
|
||||
<section id='description'>
|
||||
Model.findOne () ведет себя как .find (), но возвращает только один документ (не массив), даже если есть несколько элементов. Это особенно полезно при поиске по свойствам, которые вы объявили уникальными. Найдите только одного человека, у которого есть определенная еда в избранном, используя Model.findOne () -> Person. Используйте аргумент функции food в качестве ключа поиска.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
<section id='instructions'>
|
||||
Find just one person which has a certain food in the person's favorites, using <code>Model.findOne() -> Person</code>. Use the function argument food as search key.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
@@ -20,22 +21,9 @@ Model.findOne () ведет себя как .find (), но возвращает
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Найти один предмет должен быть успешным
|
||||
- text: Find one item should succeed
|
||||
testString: '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); })'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
||||
|
Reference in New Issue
Block a user