Skip to content

Instantly share code, notes, and snippets.

@gchumillas
Last active October 5, 2021 06:29
Show Gist options
  • Save gchumillas/fa5e65fe075f11f31e5a20a996cdfc46 to your computer and use it in GitHub Desktop.
Save gchumillas/fa5e65fe075f11f31e5a20a996cdfc46 to your computer and use it in GitHub Desktop.
Code generator
import { Db } from 'mongodb'
// Increments the `count` field of the `codes` collection and returns it.
// This function is "thread safety".
//
// It's important to update and find the document at the same time.
// Otherwise a "race condition" may arise.
const newCode = async (db: Db, name: string) => {
const { value: { count } } = await db.collection('codes').findOneAndUpdate({ name }, { $inc: { count: 1 } }, {
upsert: true,
returnDocument: 'after'
})
return count
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment