Skip to content

Instantly share code, notes, and snippets.

@grantcarthew
Last active June 20, 2018 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grantcarthew/fb0f9f52118a5fcad836b39b47d55108 to your computer and use it in GitHub Desktop.
Save grantcarthew/fb0f9f52118a5fcad836b39b47d55108 to your computer and use it in GitHub Desktop.

Mongoose Code Snippets

Targeted Version: 5.1.6

Find Or Create

This will update the document on every call. Not the best option however it is atomic.

Ref: findOneAndUpdate

const Model = require('model')
const options = {
  new: true,
  setDefaultsOnInsert: true,
  runValidators: true,
  upsert: true
}

function findOrCreate (query, update) {
  return Model.findOneAndUpdate(query, update, options)
}

Find And Increment

Returns a document if found and updates a views field.

Ref: findOneAndUpdate

const Model = require('model')
const update = { $inc: { views: 1 } }

function findAndIncrement (_id) {
  return md.Activity.findOneAndUpdate({ _id }, update)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment