developerasun / myCodeBox-web

Open source code box for web developers.
Apache License 2.0
5 stars 0 forks source link

[RESEARCH] MongoDB/CRUD : findOneAndDelete #241

Open developerasun opened 2 years ago

developerasun commented 2 years ago

topic :

read this

Remove a single document from a collection based on a query and return a document with the same form as the document immediately before it was deleted. Unlike collection.deleteOne(), this action allows you to atomically find and delete a document with the same command. This avoids the risk of other update operations changing the document between separate find and delete operations.

example

To call the collection.findOneAndDelete() action from a Function, get a collection handle with database.collection() then call the handle's findOneAndUpdate() method.

// Find the first document that has a quantity greater than 25
const query = { "quantity": { "$gte": 25 } };
// Sort the documents in order of descending quantity before
// deleting the first one.
const options = {
  "sort": { "quantity": -1 }
}

return itemsCollection.findOneAndDelete(query, options)
  .then(deletedDocument => {
    if(deletedDocument) {
      console.log(`Successfully deleted document that had the form: ${deletedDocument}.`)
    } else {
      console.log("No document matches the provided query.")
    }
    return deletedDocument
  })
  .catch(err => console.error(`Failed to find and delete document: ${err}`))

see also #240

reference