Skip to content

Instantly share code, notes, and snippets.

@luisjunco
Last active February 28, 2024 14:31
Show Gist options
  • Save luisjunco/28e17edcc21868753ea6d60983427623 to your computer and use it in GitHub Desktop.
Save luisjunco/28e17edcc21868753ea6d60983427623 to your computer and use it in GitHub Desktop.
Mongoose methods cheat sheet

Mongoose static methods:

Create

  • Model.create(data)
  • Model.insertMany(arr)

Read

  • Model.find()
    • find all documents in a collection
    • note: returns an array (even if there's zero or one documents)
  • Model.find(filter)
    • find all documents that match the filter.
    • ex: Model.find({price: {$gt: 20} })
  • Model.findOne(filter)
  • Model.findById(id)

Update

  • Model.updateMany(filter, update [, options])
  • Model.findOneAndUpdate(filter, update [, options])
  • Model.findByIdAndUpdate(id, update [, options])
    • By default, it will return the document before the update was applied.
    • In case you want to receive the updated document, you can pass a third argument with { new: true }.
    • Example: Model.findByIdAndUpdate(id, update, { new: true })

Delete

  • Model.deleteMany(filter)
  • Model.deleteOne(filter)
  • Model.findByIdAndDelete(id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment