Commands
Adonis ODM provides several ace commands to help you work with MongoDB models and database operations efficiently.
Available Commands
Configuration
# Configure the package (run this after installation)
node ace configure adonis-odm
Model Generation
make:odm-model
Generate a new ODM model with the proper structure and decorators:
node ace make:odm-model User
Generated file structure:
import { BaseModel, column } from "adonis-odm";
import { DateTime } from "luxon";
export default class User extends BaseModel {
@column({ isPrimary: true })
declare _id: string;
@column.dateTime({ autoCreate: true })
declare createdAt: DateTime;
@column.dateTime({ autoCreate: true, autoUpdate: true })
declare updatedAt: DateTime;
}
Options:
--exact
- Generate model with exact name (no pluralization)--connection=<name>
- Specify which connection to use
Examples:
# Generate a User model
node ace make:odm-model User
# Generate with exact name (no pluralization)
node ace make:odm-model UserProfile --exact
# Generate for specific connection
node ace make:odm-model AnalyticsEvent --connection=analytics
Database Seeders
make:odm-seeder
Generate a new database seeder for populating collections with test data:
# Create a basic seeder
node ace make:odm-seeder User
# Create seeder in subdirectory
node ace make:odm-seeder admin/User
odm:seed
Run database seeders to populate your collections:
# Run all seeders
node ace odm:seed
# Run specific seeder files
node ace odm:seed --files="./database/seeders/user_seeder.ts"
# Run multiple specific seeders
node ace odm:seed --files="./database/seeders/user_seeder.ts,./database/seeders/post_seeder.ts"
# Run seeders interactively (choose which ones to run)
node ace odm:seed --interactive
# Run seeders for specific connection
node ace odm:seed --connection=analytics
Options:
--files
- Comma-separated list of seeder files to run--interactive
- Choose seeders to run interactively--connection
- Specify database connection to use
Database Operations
# Test database connection (coming soon)
node ace mongodb:status
# Show database information (coming soon)
node ace mongodb:info
The following commands are planned for future releases:
mongodb:status
(Coming Soon)
Check the status of your MongoDB connections.
mongodb:info
(Coming Soon)
Display detailed information about your MongoDB setup including server version, database statistics, and collection information.
Command Examples
Setting Up a New Project
# 1. Install Adonis ODM
npm i adonis-odm
# 2. Configure the package
node ace configure adonis-odm
# 3. Create your first model
node ace make:odm-model User
# 4. Create a seeder for test data
node ace make:odm-seeder User
# 5. Run the seeder
node ace odm:seed --files="./database/seeders/user_seeder.ts"
Creating Models for Different Purposes
# User management models
node ace make:odm-model User
node ace make:odm-model UserProfile --exact
node ace make:odm-model UserPreferences --exact
# Blog models
node ace make:odm-model Post
node ace make:odm-model Comment
node ace make:odm-model Category
# Analytics models (different connection)
node ace make:odm-model AnalyticsEvent --connection=analytics
node ace make:odm-model PageView --connection=analytics
Custom Commands
You can create custom commands that work with Adonis ODM:
Creating a Custom Command
node ace make:command SyncUsers
Example Custom Command
import { BaseCommand } from "@adonisjs/core/ace";
import { CommandOptions } from "@adonisjs/core/types/ace";
import User from "#models/user";
export default class SyncUsers extends BaseCommand {
static commandName = "sync:users";
static description = "Sync users from external API";
static options: CommandOptions = {
startApp: true,
};
async run() {
this.logger.info("Starting user sync...");
try {
// Your sync logic here
const users = await this.fetchUsersFromAPI();
for (const userData of users) {
await User.updateOrCreate({ email: userData.email }, userData);
}
this.logger.success(`Synced ${users.length} users`);
} catch (error) {
this.logger.error("Sync failed:", error.message);
this.exitCode = 1;
}
}
private async fetchUsersFromAPI() {
// API call logic
return [];
}
}
Using Database Service in Commands
import { BaseCommand } from "@adonisjs/core/ace";
import db from "adonis-odm/services/db";
export default class DatabaseMaintenance extends BaseCommand {
static commandName = "db:maintenance";
static description = "Perform database maintenance tasks";
async run() {
// Use transactions in commands
await db.transaction(async (trx) => {
// Cleanup old records
await User.query({ client: trx })
.where("lastLoginAt", "<", DateTime.now().minus({ days: 365 }))
.delete();
// Update statistics
await this.updateStatistics(trx);
});
this.logger.success("Maintenance completed");
}
private async updateStatistics(trx: any) {
// Statistics update logic
}
}
Best Practices
1. Use Transactions for Data Integrity
await db.transaction(async (trx) => {
// All operations within transaction
await Model1.create(data1, { client: trx });
await Model2.create(data2, { client: trx });
});
2. Handle Errors Gracefully
try {
await this.performOperation();
this.logger.success("Operation completed");
} catch (error) {
this.logger.error("Operation failed:", error.message);
this.exitCode = 1;
}
3. Provide Progress Feedback
const total = await User.query().count();
let processed = 0;
for (const user of users) {
await this.processUser(user);
processed++;
if (processed % 100 === 0) {
this.logger.info(`Progress: ${processed}/${total}`);
}
}
Troubleshooting
Command Not Found
If commands are not available:
- Ensure the provider is registered in
adonisrc.ts
- Restart your development server
- Check that the package is properly installed
Connection Issues
If database commands fail:
- Check your environment variables
- Verify MongoDB is running
- Test connection manually
Next Steps
Now that you know about the available commands:
- Learn about Models - Create your data models
- Explore Database Seeders - Populate your database with test data
- Explore Query Builder - Build complex queries
- Work with Transactions - Ensure data consistency