From e1bae44036b50c84d22b79f270c7c8a274aa7cfe Mon Sep 17 00:00:00 2001
From: Shaun Hamilton <51722130+Sky020@users.noreply.github.com>
Date: Tue, 3 Nov 2020 14:22:55 +0000
Subject: [PATCH] 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>
---
...-query-helpers-to-narrow-search-results.md | 33 +++++++++--
.../mongodb-and-mongoose/create-a-model.md | 56 ++++++++++++-------
.../create-and-save-a-record-of-a-model.md | 19 ++++++-
.../create-many-records-with-model.create.md | 27 +++++++--
...delete-many-documents-with-model.remove.md | 24 ++++++--
...-document-using-model.findbyidandremove.md | 21 ++++++-
.../install-and-set-up-mongoose.md | 39 +++++++++----
...-updates-by-running-find-edit-then-save.md | 20 +++++--
...a-document-using-model.findoneandupdate.md | 25 +++++++--
.../use-model.find-to-search-your-database.md | 22 ++++++--
....findbyid-to-search-your-database-by-id.md | 21 ++++++-
...le-matching-document-from-your-database.md | 21 +++++--
12 files changed, 258 insertions(+), 70 deletions(-)
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/chain-search-query-helpers-to-narrow-search-results.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/chain-search-query-helpers-to-narrow-search-results.md
index b2a82ddcef..b96a486b98 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/chain-search-query-helpers-to-narrow-search-results.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/chain-search-query-helpers-to-narrow-search-results.md
@@ -6,33 +6,58 @@ forumTopicId: 301533
---
## Description
+
-If you don’t 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 ‘famous’ ones.
+
+If you don’t 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.
+
## Instructions
+
-Find people who like burrito
. 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()
.
+
+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,
+
## 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); })
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-a-model.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-a-model.md
index f06948d978..9a88fa2efc 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-a-model.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-a-model.md
@@ -6,22 +6,23 @@ forumTopicId: 301535
---
## Description
+
-CRUD 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.
+**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). We’ll 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). We’ll 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.
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) {
## Instructions
-
-Create a person having this prototype :
-
-- 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 mongoose docs.
+
+
+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 Mongoose docs.
+
+Now, create a model called `Person` from the `personSchema`.
+
## 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); })
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model.md
index 05c6ad868d..57b680e7ed 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model.md
@@ -6,13 +6,18 @@ forumTopicId: 301536
---
## Description
+
+
In this challenge you will have to create and save a record of a model.
+
## Instructions
+
-Create a document instance using the Person
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 Person Schema. 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.
+
+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) {
## 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); })
+
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-many-records-with-model.create.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-many-records-with-model.create.md
index 844d682d71..06d4a23195 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-many-records-with-model.create.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-many-records-with-model.create.md
@@ -6,34 +6,51 @@ forumTopicId: 301537
---
## Description
+
-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.
+
+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.
+
## Instructions
+
-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.
+
+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.
+
## 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); })
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/delete-many-documents-with-model.remove.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/delete-many-documents-with-model.remove.md
index 83d0c6f1a4..332943dcd1 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/delete-many-documents-with-model.remove.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/delete-many-documents-with-model.remove.md
@@ -6,34 +6,48 @@ forumTopicId: 301538
---
## Description
+
-Model.remove()
is useful to delete all the documents matching given criteria.
+
+`Model.remove()` is useful to delete all the documents matching given criteria.
+
## Instructions
+
-Delete all the people whose name is “Mary”, using Model.remove()
. Pass it to a query document with the name
field set, and of course a callback.
-Note: The Model.remove()
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 done()
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()` 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 `done()` callback, since we use it in tests.
+
## 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); })
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/delete-one-document-using-model.findbyidandremove.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/delete-one-document-using-model.findbyidandremove.md
index 721d16a80b..131eaad276 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/delete-one-document-using-model.findbyidandremove.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/delete-one-document-using-model.findbyidandremove.md
@@ -6,33 +6,48 @@ forumTopicId: 301539
---
## Description
+
-Delete one person by the person's _id
. You should use one of the methods findByIdAndRemove()
or findOneAndRemove()
. They 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.
+
+`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.
+
## Instructions
+
+Modify the `removeById` function to delete one person by the person's `_id`. You should use one of the methods `findByIdAndRemove()` or `findOneAndRemove()`.
+
## 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); })
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/install-and-set-up-mongoose.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/install-and-set-up-mongoose.md
index 5a996cca25..a250bd33be 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/install-and-set-up-mongoose.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/install-and-set-up-mongoose.md
@@ -6,41 +6,60 @@ forumTopicId: 301540
---
## Description
+
-Add mongodb and mongoose to the project’s package.json. Then require mongoose. Store your MongoDB Atlas database URI in the 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:
+
+In this challenge, you will import the required projects, and connect to your Atlas database.
+
+
+
+## Instructions
+
+
+
+Add `mongodb` and `mongoose` to the project’s `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(, { useNewUrlParser: true, useUnifiedTopology: true });
+mongoose.connect(, { useNewUrlParser: true, useUnifiedTopology: true });
```
-
-
## 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); })
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save.md
index 256be77225..fd5836f071 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save.md
@@ -6,37 +6,49 @@ forumTopicId: 301541
---
## 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 : Model.update()
. It is bound to the low-level mongo driver. It can bulk edit many documents matching certain criteria, but it doesn’t 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 doesn’t send back the updated document, only a 'status' message. Furthermore, it makes model validations difficult, because it just directly calls the mongo driver.
+
## Instructions
+
-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
.
+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`.
-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)
+**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)
## 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); })
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/perform-new-updates-on-a-document-using-model.findoneandupdate.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/perform-new-updates-on-a-document-using-model.findoneandupdate.md
index 8f434445da..20e2d06bea 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/perform-new-updates-on-a-document-using-model.findoneandupdate.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/perform-new-updates-on-a-document-using-model.findoneandupdate.md
@@ -6,34 +6,49 @@ forumTopicId: 301542
---
## 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. findByIdAndUpdate()
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.
+
## Instructions
+
-Find a person by Name
and set the person's age to 20. Use the function parameter personName
as 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.
+
+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.
+
## 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); })
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-database.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-database.md
index 0f5fc7b99b..38b08f8c9e 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-database.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-database.md
@@ -6,34 +6,48 @@ forumTopicId: 301543
---
## Description
+
-Find all the people having a given name, using Model.find() -> [Person]
-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. Check it in the docs. Use the function argument personName
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.
+
## 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.
+
## 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); })
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.findbyid-to-search-your-database-by-id.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.findbyid-to-search-your-database-by-id.md
index c7007ed3cc..d64d176c62 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.findbyid-to-search-your-database-by-id.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.findbyid-to-search-your-database-by-id.md
@@ -6,32 +6,47 @@ forumTopicId: 301544
---
## Description
+
-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.
+
+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.
+
## Instructions
+
-Find the (only!!) person having a given _id
, using Model.findById() -> Person
. Use the function argument personId
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.
+
## 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); })
```
## Challenge Seed
+
## Solution
+
```js
diff --git a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.findone-to-return-a-single-matching-document-from-your-database.md b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.findone-to-return-a-single-matching-document-from-your-database.md
index cee57f2209..e3096f0903 100644
--- a/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.findone-to-return-a-single-matching-document-from-your-database.md
+++ b/curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/use-model.findone-to-return-a-single-matching-document-from-your-database.md
@@ -6,33 +6,46 @@ forumTopicId: 301545
---
## Description
+
-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.
+
+`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.
+
## Instructions
+
-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.
+
+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.
+
## 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); })
```
## Challenge Seed
+
## Solution
+