Skip to content

Instantly share code, notes, and snippets.

@luisjunco
Last active May 22, 2024 11:26
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])
    • Note 1: by default, Mongoose 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 })
    • Note 2: by default, Mongoose does not run validation on updates.
      • This can be configured on individual updates with this syntax: Model.findByIdAndUpdate(id, update, { new: true, runValidators: true })
      • or, it can be turned on for all updates, adding this line: mongoose.set('runValidators', 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