Last active
October 5, 2021 06:29
-
-
Save gchumillas/fa5e65fe075f11f31e5a20a996cdfc46 to your computer and use it in GitHub Desktop.
Code generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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