55 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			Markdown
		
	
	
	
	
	
			
		
		
	
	
			55 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			Markdown
		
	
	
	
	
	
| ---
 | ||
| id: 587d7fb8367417b2b2512c0e
 | ||
| title: 'Perform Classic Updates by Running Find, Edit, then Save'
 | ||
| challengeType: 2
 | ||
| forumTopicId: 301541
 | ||
| dashedName: perform-classic-updates-by-running-find-edit-then-save
 | ||
| ---
 | ||
| 
 | ||
| # --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.
 | ||
| 
 | ||
| # --instructions--
 | ||
| 
 | ||
| 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)
 | ||
| 
 | ||
| # --hints--
 | ||
| 
 | ||
| Find-edit-update an item should succeed
 | ||
| 
 | ||
| ```js
 | ||
| (getUserInput) =>
 | ||
|   $.post(getUserInput('url') + '/_api/find-edit-save', {
 | ||
|     name: 'Poldo',
 | ||
|     age: 40,
 | ||
|     favoriteFoods: ['spaghetti']
 | ||
|   }).then(
 | ||
|     (data) => {
 | ||
|       assert.equal(data.name, 'Poldo', 'item.name is not what is expected');
 | ||
|       assert.equal(data.age, 40, 'item.age is not what expected');
 | ||
|       assert.deepEqual(
 | ||
|         data.favoriteFoods,
 | ||
|         ['spaghetti', 'hamburger'],
 | ||
|         'item.favoriteFoods is not what expected'
 | ||
|       );
 | ||
|       assert.equal(data.__v, 1, 'The item should be previously edited');
 | ||
|     },
 | ||
|     (xhr) => {
 | ||
|       throw new Error(xhr.responseText);
 | ||
|     }
 | ||
|   );
 | ||
| ```
 | ||
| 
 | ||
| # --solutions--
 | ||
| 
 | ||
| ```js
 | ||
| /**
 | ||
|   Backend challenges don't need solutions, 
 | ||
|   because they would need to be tested against a full working project. 
 | ||
|   Please check our contributing guidelines to learn more.
 | ||
| */
 | ||
| ```
 |