feat(learn): migrate mongodb-mongoose instructions to learn (#39970)

* feat(learn): migrate mongodb-mongoose instructions to learn

* remove extraneous quotation mark

* update with boilerplate change

* grammar changes on instructions

Co-authored-by: Randell Dawson <5313213+RandellDawson@users.noreply.github.com>

Co-authored-by: Randell Dawson <5313213+RandellDawson@users.noreply.github.com>
This commit is contained in:
Shaun Hamilton
2020-11-03 14:22:55 +00:00
committed by GitHub
parent b0e3d7369b
commit e1bae44036
12 changed files with 258 additions and 70 deletions

View File

@ -6,33 +6,58 @@ forumTopicId: 301533
---
## Description
<section id='description'>
If you dont pass the callback as the last argument to <code>Model.find()</code> (or to the other search methods), the query is not executed. You can store the query in a variable for later use. This kind of object enables you to build up a query using chaining syntax. The actual db search is executed when you finally chain the method <code>.exec()</code>. You always need to pass your callback to this last method. There are many query helpers, here well use the most famous ones.
If you dont pass the callback as the last argument to `Model.find()` (or to the other search methods), the query is not executed. You can store the query in a variable for later use. This kind of object enables you to build up a query using chaining syntax. The actual db search is executed when you finally chain the method `.exec()`. You always need to pass your callback to this last method. There are many query helpers, here we'll use the most commonly used.
</section>
## 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>.
Modify the `queryChain` function to find people who like the food specified by the variable named `foodToSearch`. Sort them by `name`, limit the results to two documents, and hide their age. Chain `.find()`, `.sort()`, `.limit()`, `.select()`, and then `.exec()`. Pass the `done(err, data)` callback to `exec()`.
### Further Readings
If you are eager to learn and want to go deeper, You may look at:
- Indexes ( very important for query efficiency ),
- Pre/Post hooks,
- Validation,
- Schema Virtuals and Model, Static, and Instance methods,
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })'
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

View File

@ -6,22 +6,23 @@ forumTopicId: 301535
---
## Description
<section id='description'>
<b>C</b>RUD Part I - CREATE
First of all we need a Schema. Each schema maps to a MongoDB collection. It defines the shape of the documents within that collection.
Schemas are building block for Models. They can be nested to create complex models, but in this case well keep things simple.
A model allows you to create instances of your objects, called documents.
**C**RUD Part I - CREATE
First of all we need a Schema. Each schema maps to a MongoDB collection. It defines the shape of the documents within that collection. Schemas are building block for Models. They can be nested to create complex models, but in this case we'll keep things simple. A model allows you to create instances of your objects, called documents.
Repl.it is a real server, and in real servers the interactions with the database happen in handler functions. These functions are executed when some event happens (e.g. someone hits an endpoint on your API). Well follow the same approach in these exercises. The `done()` function is a callback that tells us that we can proceed after completing an asynchronous operation such as inserting, searching, updating, or deleting. It's following the Node convention, and should be called as `done(null, data)` on success, or `done(err)` on error.
Repl.it is a real server, and in real servers the interactions with the db happen in handler functions. These function are executed when some event happens (e.g. someone hits an endpoint on your API). Well follow the same approach in these exercises. The <code>done()</code> function is a callback that tells us that we can proceed after completing an asynchronous operation such as inserting, searching, updating or deleting. Its following the Node convention and should be called as <code>done(null, data)</code> on success, or <code>done(err)</code> on error.
Warning - When interacting with remote services, errors may occur!
```js
/* Example */
var someFunc = function(done) {
const someFunc = function(done) {
//... do something (risky) ...
if(error) return done(error);
if (error) return done(error);
done(null, result);
};
```
@ -29,39 +30,52 @@ var someFunc = function(done) {
</section>
## 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 id='instructions'>
Create a person schema called `personSchema` having this prototype:
```markup
- Person Prototype -
--------------------
name : string [required]
age : number
favoriteFoods : array of strings (*)
```
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>.
Now, create a model called `Person` from the `personSchema`.
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })'
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

View File

@ -6,13 +6,18 @@ forumTopicId: 301536
---
## Description
<section id='description'>
In this challenge you will have to create and save a record of a model.
</section>
## 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.
Within the `createAndSavePerson` function, create a document instance using the `Person` model constructor you built before. Pass to the constructor an object having the fields `name`, `age`, and `favoriteFoods`. Their types must conform to the ones in the `personSchema`. Then, call the method `document.save()` 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 */
@ -26,22 +31,32 @@ person.save(function(err, data) {
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })'
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

View File

@ -6,34 +6,51 @@ forumTopicId: 301537
---
## Description
<section id='description'>
Sometimes you need to create many instances of your models, e.g. when seeding a database with initial data. <code>Model.create()</code> takes an array of objects like <code>[{name: 'John', ...}, {...}, ...]</code> as the first argument, and saves them all in the db.
Sometimes you need to create many instances of your models, e.g. when seeding a database with initial data. `Model.create()` takes an array of objects like `[{name: 'John', ...}, {...}, ...]` as the first argument, and saves them all in the db.
</section>
## Instructions
<section id='instructions'>
Modify the <code>createManyPeople</code> function to create many people using <code>Model.create()</code> with the argument <code>arrayOfPeople</code>.
<strong>Note: </strong> You can reuse the model you instantiated in the previous exercise.
Modify the `createManyPeople` function to create many people using `Model.create()` with the argument `arrayOfPeople`.
**Note:** You can reuse the model you instantiated in the previous exercise.
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })'
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

View File

@ -6,34 +6,48 @@ forumTopicId: 301538
---
## Description
<section id='description'>
<code>Model.remove()</code> is useful to delete all the documents matching given criteria.
`Model.remove()` is useful to delete all the documents matching given criteria.
</section>
## 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> doesnt return the deleted document, but a JSON object containing the outcome of the operation, and the number of items affected. Dont forget to pass it to the <code>done()</code> callback, since we use it in tests.
Modify the `removeManyPeople` function to delete all the people whose name is within the variable `nameToRemove`, using `Model.remove()`. Pass it to a query document with the `name` field set, and a callback.
**Note:** The `Model.remove()` doesnt return the deleted document, but a JSON object containing the outcome of the operation, and the number of items affected. Dont forget to pass it to the `done()` callback, since we use it in tests.
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })'
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

View File

@ -6,33 +6,48 @@ forumTopicId: 301539
---
## Description
<section id='description'>
Delete one person by the person's <code>_id</code>. You should use one of the methods <code>findByIdAndRemove()</code> or <code>findOneAndRemove()</code>. They are like the previous update methods. They pass the removed document to the db. As usual, use the function argument <code>personId</code> as the search key.
`findByIdAndRemove` and `findOneAndRemove` are like the previous update methods. They pass the removed document to the db. As usual, use the function argument `personId` as the search key.
</section>
## Instructions
<section id='instructions'>
Modify the `removeById` function to delete one person by the person's `_id`. You should use one of the methods `findByIdAndRemove()` or `findOneAndRemove()`.
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })'
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

View File

@ -6,41 +6,60 @@ forumTopicId: 301540
---
## Description
<section id='description'>
Add mongodb and mongoose to the projects package.json. Then require mongoose. Store your MongoDB Atlas database URI in the private <code>.env</code> file as MONGO_URI. Surround the the URI with single or double quotes and make sure no space exists between both the variable and the `=` and the value and `=`. Connect to the database using the following syntax:
In this challenge, you will import the required projects, and connect to your Atlas database.
</section>
## Instructions
<section id='instructions'>
Add `mongodb` and `mongoose` to the projects `package.json`. Then, require mongoose as `mongoose` in `myApp.js`. Store your MongoDB Atlas database URI in a private `.env` file as `MONGO_URI`. Surround the the URI with single or double quotes, and make sure no space exists between both the variable and the `=`, and the value and `=`. Connect to the database using the following syntax:
```js
mongoose.connect(<Your URI>, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connect(<Your URI>, { useNewUrlParser: true, useUnifiedTopology: true });
```
</section>
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })'
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); })'
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); })'
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

View File

@ -6,37 +6,49 @@ forumTopicId: 301541
---
## Description
<section id='description'>
In the good old days this was what you needed to do if you wanted to edit a document and be able to use it somehow e.g. sending it back in a server response. Mongoose has a dedicated updating method : <code>Model.update()</code>. It is bound to the low-level mongo driver. It can bulk edit many documents matching certain criteria, but it doesnt send back the updated document, only a status message. Furthermore it makes model validations difficult, because it just directly calls the mongo driver.
In the good old days, this was what you needed to do if you wanted to edit a document, and be able to use it somehow (e.g. sending it back in a server response). Mongoose has a dedicated updating method: `Model.update()`. It is bound to the low-level mongo driver. It can bulk-edit many documents matching certain criteria, but it doesnt send back the updated document, only a 'status' message. Furthermore, it makes model validations difficult, because it just directly calls the mongo driver.
</section>
## 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 &quot;hamburger&quot; to the list of the person&apos;s <code>favoriteFoods</code> (you can use <code>Array.push()</code>). Then - inside the find callback - <code>save()</code> the updated <code>Person</code>.
Modify the `findEditThenSave` function to find a person by `_id` (use any of the above methods) with the parameter `personId` as search key. Add `"hamburger"` to the list of the person's `favoriteFoods` (you can use `Array.push()`). Then - inside the find callback - `save()` the updated `Person`.
<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 case, <code>favoriteFoods</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)
**Note:** This may be tricky, if in your Schema, you declared `favoriteFoods` as an Array, without specifying the type (i.e. `[String]`). In that case, `favoriteFoods` defaults to Mixed type, and you have to manually mark it as edited using `document.markModified('edited-field')`. See [Mongoose documentation](https://mongoosejs.com/docs/schematypes.html#Mixed)
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })"
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

View File

@ -6,34 +6,49 @@ forumTopicId: 301542
---
## Description
<section id='description'>
Recent versions of mongoose have methods to simplify documents updating. Some more advanced features (i.e. pre/post hooks, validation) behave differently with this approach, so the Classic method is still useful in many situations. <code>findByIdAndUpdate()</code> can be used when searching by Id.
Recent versions of Mongoose have methods to simplify documents updating. Some more advanced features (i.e. pre/post hooks, validation) behave differently with this approach, so the classic method is still useful in many situations. `findByIdAndUpdate()` can be used when searching by id.
</section>
## Instructions
<section id='instructions'>
Find a person by <code>Name</code> and set the person&apos;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.
Modify the `findAndUpdate` function to find a person by `Name` and set the person's age to `20`. Use the function parameter `personName` as the search key.
**Note:** You should return the updated document. To do that, you need to pass the options document `{ new: true }` as the 3rd argument to `findOneAndUpdate()`. By default, these methods return the unmodified object.
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })'
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

View File

@ -6,34 +6,48 @@ forumTopicId: 301543
---
## Description
<section id='description'>
Find all the people having a given name, using <code>Model.find() -> [Person]</code>
In its simplest usage, <code>Model.find()</code> accepts a query document (a JSON object) as the first argument, then a callback. It returns an array of matches. It supports an extremely wide range of search options. Check it in the docs. Use the function argument <code>personName</code> as search key.
In its simplest usage, `Model.find()` accepts a query document (a JSON object) as the first argument, then a callback. It returns an array of matches. It supports an extremely wide range of search options. Read more in the docs.
</section>
## Instructions
<section id='instructions'>
Modify the `findPeopleByName` function to find all the people having a given name, using `Model.find() -> [Person]`
Use the function argument `personName` as the search key.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Find all items corresponding to a criteria should succeed
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); })'
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

View File

@ -6,32 +6,47 @@ forumTopicId: 301544
---
## Description
<section id='description'>
When saving a document, mongodb automatically adds the field <code>_id</code>, and set it to a unique alphanumeric key. Searching by <code>_id</code> is an extremely frequent operation, so mongoose provides a dedicated method for it.
When saving a document, MongoDB automatically adds the field `_id`, and set it to a unique alphanumeric key. Searching by `_id` is an extremely frequent operation, so Mongoose provides a dedicated method for it.
</section>
## 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.
Modify the `findPersonById` to find the only person having a given `_id`, using `Model.findById() -> Person`. Use the function argument `personId` as the search key.
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })"
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

View File

@ -6,33 +6,46 @@ forumTopicId: 301545
---
## Description
<section id='description'>
<code>Model.findOne()</code> behaves like <code>.find()</code>, but it returns only one document (not an array), even if there are multiple items. It is especially useful when searching by properties that you have declared as unique.
`Model.findOne()` behaves like `.find()`, but it returns only one document (not an array), even if there are multiple items. It is especially useful when searching by properties that you have declared as unique.
</section>
## Instructions
<section id='instructions'>
Find just one person which has a certain food in the person&apos;s favorites, using <code>Model.findOne() -> Person</code>. Use the function argument food as search key.
Modify the `findOneByFood` function to find just one person which has a certain food in the person's favorites, using `Model.findOne() -> Person`. Use the function argument `food` as search key.
</section>
## Tests
<section id='tests'>
```yml
tests:
- 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); })'
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