The firstOrCreate() method is a convenient way to retrieve an existing model or create a new one if it doesn’t exist. This is particularly useful for ensuring unique records or preventing duplicates.
// Ensure a book with this ISBN existsconst book = await Book.firstOrCreate( { isbn: '9780486284736' }, { title: 'Pride and Prejudice', pages: 279, authorId: 'author-1' });// If the book already exists, no duplicate is created
Model default values are automatically applied during creation:
Copy
class Book extends BaseModel { public isAvailable = true; public isbn = ''; public title = '';}const book = await Book.firstOrCreate( { isbn: '9780140449266' }, { title: 'Crime and Punishment', pages: 688 });// book.isAvailable is true (from model defaults)
Use unique identifiers in your filter (like email, ISBN, or slug) to avoid creating unintended duplicates.
Be aware that firstOrCreate() is not atomic. In high-concurrency scenarios, two requests might both not find a record and both attempt to create it. Consider using unique indexes in MongoDB for critical fields.
// Good: Using a unique identifierconst user = await User.firstOrCreate( { email: 'unique@example.com' }, { name: 'User Name' });// Avoid: Using non-unique fieldsconst user = await User.firstOrCreate( { name: 'John' }, // Many users might have this name { email: 'john123@example.com' });