- Advanced Node.js Development
- Andrew Mead
- 487字
- 2021-08-27 19:05:57
The findOneAndDelete method
Most of the time, when I'm deleting a document, I only have the ID. This means that I don't exactly know what the text is or the completed status, and that can be really useful depending on your user interface. For example, if I delete a Todo, maybe I want to show that next, saying You deleted the Todo that says Eat lunch, with a little undo button in case they didn't mean to take that action. Getting the data back as well as deleting it can be really useful.
In order to explore findOneAndDelete, we're going to once again target the Todo where the text equals Eat lunch. I'm going to go ahead and comment out deleteOne, and next we can get started by accessing the appropriate collection. The method is called findOneAndDelete. The findOneAndDelete method takes a very similar set of arguments. The only thing we need to pass in is the query. This is going to be identical to the ones we have in the previous screenshot. This time though, let's go ahead and target Todos that had a completed value set to false.
Now there are two Todos that fit this query, but once again we're using a findOne method, which means it's only going to target the first one it sees, the one with a text property of Something to do. Back in Atom, we can get this done by targeting Todos where completed equals false. Now, instead of getting back a result object with an ok property and an n property, the findOneAndDelete method actually gets that document back. This means we can tack on a then call, we can get our result, and we can print it to the screen once again with console.log(result):
//findOneAndDelete
db.collection('Todos').findOneAndDelete({completed: false}).then((result) => { console.log(result); });
Now that we have this in place, let's test things out over in the Terminal. In the Terminal, I'm going to shut down the script and start it up again:
We get a few different things in our result object. We do get an ok set to 1, letting us know things went as planned. We have a lastErrorObject; we'll talk about that in just a second; and we have our value object. This is the actual document we deleted. This is why the findOneAndDelete method is super handy. It gets that document back as well as deleting it.
Now in this particular case, the lastErrorObject, once again just has our n property, and we can see the number of Todos that were deleted. There is other information that could potentially be in lastErrorObject, but that's only going to happen when we use other methods, so we'll look at that when the time comes. For now, when you delete a Todo, we just get the number back.
With this in place, we now have three different ways we can target our MongoDB documents and remove them.