You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The note to be updated is modified directly in the database using the findByIdAndUpdate method. If no object is found in the database with the given id, the value of the variable updatedNote is null, and the query responds with the status code <i>404 Not Found</i>.
910
+
The note to be updated is first fetched from the database using the _findById_ method. If no object is found in the database with the given id, the value of the variable _note_ is _null_, and the query responds with the status code <i>404 Not Found</i>.
911
+
912
+
If an object with the given id is found, its _content_ and _important_ fields are updated with the data provided in the request, and the modified note is saved to the database using the _save()_ method. The HTTP request responds by sending the updated note in the response.
907
913
908
-
If an object with the given id is found, its content and important fields are updated with the data provided in the request, and the database returns the updated note. The HTTP request responds by sending this updated note in the response.
914
+
One notable point is that the code now has nested promises, meaning that within the outer _.then_ method, another [promise chain](https://javascript.info/promise-chaining) is defined:
915
+
916
+
```js
917
+
.then(note=> {
918
+
if (!note) {
919
+
returnresponse.status(404).end()
920
+
}
921
+
922
+
note.content= content
923
+
note.important= important
924
+
925
+
// highlight-start
926
+
returnnote.save().then((updatedNote) => {
927
+
response.json(updatedNote)
928
+
})
929
+
// highlight-end
930
+
```
909
931
910
-
In the options given to findByIdAndUpdate, the value of the <i>new</i> field is set to <i>true</i>. This tells Mongoose to return the updated document instead of the original version from before the update.
932
+
Usually, this is not recommended because it can make the code difficult to read. In this case, however, the solution works because it ensures that the _.then_ block following the _save()_ method is only executed if a note with the given id is found in the database and the _save()_ method is called. In the fourth part of the course, we will explore the async/await syntax, which offers an easier and clearer way to handle such situations.
911
933
912
934
After testing the backend directly with Postman or the VS Code REST client, we can verify that it seems to work. The frontend also appears to work with the backend using the database.
0 commit comments