API Design in Node.js, v3 API Design in Node.js, v3

Update & Delete a Document Solution

Check out a free preview of the full API Design in Node.js, v3 course:
The "Update & Delete a Document Solution" Lesson is part of the full, API Design in Node.js, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Scott live codes the solution to the tests where an authenticated user and id must be found to update, and a 400 error must result if no document is found. The first document by a specified authenticated user and id must also be removed, and a 400 error must result if no document is found.

Get Unlimited Access Now

Transcript from the "Update & Delete a Document Solution" Lesson

[00:00:00]
>> Scott Moss: And then now for an update one. Well, it says find a doc by authenticating a user and ID to update and 400 if no doc. Okay, so what we'll do is const doc = await model. .findOneAndUpdate. The reason I chose findOneUpdate is because I have two parameters that I need to find by, the ID of the document itself, and then the authenticated user.

[00:00:34] If it was just the ID of the document I could do find by ID and update, but because I have more than just an ID I have to use findOne. So, for _ID, it's going to be req.prams.id and then for creativei which is the user it's going to be req.user._id.

[00:00:56] So that's defined, and then the update is going to be whatever they posted to the body. So req.body. Whatever that is, that's what the update body is supposed to be. Because this is res we want to send back the new updated object, we put new true. Remember, we have to put that, otherwise we won't get back the updated object, we'll get back to object before it was updated, which is not what we want.

[00:01:23]
>> Scott Moss: So now that we have that, then you can just say res.status(200).json, and we can send back the data. And that will be doc.
>> Scott Moss: And then it says, it 400, if there is no doc, so what we're gonna do is say, if no doc, I say and there was nothing to find and update, then we'll just return a res.status(400).en

[00:02:02]
>> Scott Moss: So, execute those.
>> Scott Moss: Okay, if we scroll up, looks like those tests passed.
>> Scott Moss: Okay, and if the last is removeOne, very similar to updateOne,
>> Scott Moss: We are going to say doc = await model.findOneandRemove. And we're gonna do the same thing. We're gonna find by id _id, which is req.params.id.

[00:02:39] And then the createdBy, which will be req.user._id. And there's no other arguments for this to take, so we'll just do that. .exec and it looks like, so find the one to remove and then 400 if there is no doc, so if there was no doc to remove, res dot status 400 dot end.

[00:03:12] But there was, now I would just say res.status(200).json, and then select the data.
>> Scott Moss: Cool, and it looks like all those test passed