Skip to content

Instantly share code, notes, and snippets.

@mattwang44
Created April 20, 2020 18:38
Show Gist options
  • Save mattwang44/034ef80404a47d6ae87b249e7483b7a7 to your computer and use it in GitHub Desktop.
Save mattwang44/034ef80404a47d6ae87b249e7483b7a7 to your computer and use it in GitHub Desktop.
Mongo query tips
// findOneOrCreate in Mongoose:
// Return the original doc (no modification) if it can be found and create a new doc if cannot be found.
// Without `$setOnInsert`, it will update the doc if it can be found.
Model.findOneAndUpdate(
{name: 'Matt'},
{$setOnInsert: {score: 60}},
{upsert: true, new: true}
)
// Set `setDefaultsOnInsert` to true in option if need to insert with setting the default value.
// See https://mongoosejs.com/docs/defaults.html#the-setdefaultsoninsert-option
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment