Collection Methods
MongoDB collections provide static methods for CRUD operations, similar to SQL models.
CRUD Methods
find
Fetch multiple documents.
const users = await User.find({ where: { email: 'test@example.com' } });
findOne
Fetch a single document.
const user = await User.findOne({ where: { email: 'test@example.com' } });
findOneOrFail
Fetch a single document or throw if not found.
const user = await User.findOneOrFail({ where: { email: 'test@example.com' } });
insert
Insert a new document.
const user = await User.insert({ name: 'Test', email: 'test@example.com' });
insertMany
Insert multiple documents.
const users = await User.insertMany([
{ name: 'Test 1', email: 'test1@example.com' },
{ name: 'Test 2', email: 'test2@example.com' },
]);
updateRecord
Update a document by id.
user.name = 'Updated';
const updated = await User.updateRecord(user);
deleteRecord
Delete a document by id.
await User.deleteRecord(user);
Best Practices
- Always use the static methods for database operations.
- Use
findOneOrFail
for required lookups.
Next: MongoDB Query Builder