node.jsasynchronousmongoose

Why does Node Js mongoose document deletion does not execute without await?


So i am novice at Node.js, and have been checking out its mongoose package. I have a mongodb collection with a document with field name = "Test Entry" I have tried executing a .findOneAndDelete() method call on a model wrapped within a timeout, wrapped within a function.

One issue that baffles me is why this piece of code

function deleteEntry() {
  setTimeout(function () {
    Test_Model.findOneAndDelete({
      name: "Test Entry",
    });
  }, 5000);
}

deleteEntry();

does not delete the entry within mongodb

whereas

function deleteEntry() {
  setTimeout(async function () {
    await Test_Model.findOneAndDelete({
      name: "Test Entry",
    });
  }, 5000);
}

deleteEntry();

this one does.

will the mongoose method not execute unless there is a callback made of some kind. No matter if it's for vain? There were mentions of something similar in the documentation . Does the actual execution of the command occur only when there is a callback/await/then ?


Solution

  • I found exactly the same behaviour.. I just want to delete a document and don't care about the result so I thought no need for await or .then but then indeed it doesn't delete the document.

    Your link to the docs actually provides the answer:

    Mongoose queries are not promises. Queries are thenables, meaning they have a .then() method for async/await as a convenience. However, unlike promises, calling a query's .then() executes the query, so calling then() multiple times will throw an error.

    And with a bit further reading here they explain the thenable in a bit more detail: https://masteringjs.io/tutorials/fundamentals/thenable

    So in conclusion the query doesn't execute without either await or .then. But in the case you don't need either they also provide a .exec.

    Since I don't want to keep the rest of the code waiting I ended up just using the exec: SomeModel.deleteOne({ name: 'Joe' }).exec();