### Setting up MongoDB Replica Set for Development (Bash) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/installation.mdx This bash snippet provides commands to start a MongoDB instance as a replica set (`rs0`) and then initialize it from the MongoDB shell. This setup is crucial for enabling transaction support in a local development environment. ```bash # Start MongoDB with replica set mongod --replSet rs0 --dbpath /data/db # In MongoDB shell, initialize the replica set mongo > rs.initiate() ``` -------------------------------- ### Adonis ODM Project Setup Workflow (Bash) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/commands.mdx This sequence of commands outlines the typical steps to set up a new project with Adonis ODM: installing the package, configuring it, and then generating the first ODM model. ```bash # 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 ``` -------------------------------- ### Installing Wrangler CLI (Bash) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/DEPLOYMENT.md Installs the Cloudflare Wrangler CLI globally using npm, which is required for manual deployments to Cloudflare Pages. This command makes the `wrangler` command available system-wide. ```bash npm install -g wrangler ``` -------------------------------- ### Setting Up Development Environment - Docker Compose Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/README.md This sequence first copies the example environment file to `.env` for local configuration and then starts a MongoDB instance using Docker Compose in detached mode, providing a local database for development and testing. ```bash cp .env.example .env docker-compose up -d mongodb ``` -------------------------------- ### Adonis ODM Model Generation Examples (Bash) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/commands.mdx These examples demonstrate how to use `node ace make:odm-model` to generate models. It covers basic generation, using the `--exact` flag to prevent pluralization, and specifying a custom database connection with `--connection`. ```bash # 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 ``` -------------------------------- ### Setting Up Database Testing with Japa and Adonis ODM (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/database-manager.mdx This comprehensive snippet demonstrates how to set up and perform database testing using Japa runner with Adonis ODM. It includes `setup` and `teardown` hooks for cleaning the test database before and after each test, and examples for performing raw queries and handling transactions within tests. ```TypeScript import { test } from '@japa/runner' import Database from '@ioc:Adonis/Lucid/Database' test.group('Database operations', (group) => { group.each.setup(async () => { // Setup test database await Database.connection('test').collection('users').deleteMany({}) }) group.each.teardown(async () => { // Cleanup after each test await Database.connection('test').collection('users').deleteMany({}) }) test('should perform raw query', async ({ assert }) => { const result = await Database.rawQuery({ collection: 'users', operation: 'insertOne', document: { name: 'Test User', email: 'test@example.com' } }) assert.exists(result.insertedId) }) test('should handle transactions', async ({ assert }) => { const result = await Database.transaction(async (trx) => { // Transaction operations return { success: true } }) assert.isTrue(result.success) }) }) ``` -------------------------------- ### Counting Records with Adonis-ODM Aggregation (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx Illustrates how to count records, both globally and with specific conditions, using the `count` method for simple aggregations. It also shows how to perform grouped counts using `groupBy` to get counts per category. ```typescript // Simple count const userCount = await User.query().count() console.log(`Total users: ${userCount}`) // Count with conditions const activeUserCount = await User.query() .where('status', 'active') .count() // Count by groups const usersByRole = await User.query() .groupBy('role') .count() ``` -------------------------------- ### Effective Search Queries for Adonis ODM Documentation Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/search.mdx This snippet provides examples of effective search queries for different types of content within the Adonis ODM documentation. It demonstrates how to search for specific concepts, code examples, methods, and configuration settings to yield relevant results. ```Text # Search for specific concepts "query builder" "embedded documents" "relationships" # Search for code examples "User.query()" "BaseModel" "@column" # Search for specific methods "findBy" "paginate" "whereText" # Search for configuration "astro.config" "database connection" "environment variables" ``` -------------------------------- ### Usage Examples for Order Querying Functions in TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/embedded-documents.mdx This snippet provides examples of how to call the previously defined order querying functions (`findOrdersByCategory`, `findOrdersByLocation`, `findHighValueOrders`, `getOrderAnalytics`) with sample parameters, demonstrating their practical application. ```typescript // Usage const electronics = await findOrdersByCategory('Electronics') const nyOrders = await findOrdersByLocation('NY', 'New York') const highValueOrders = await findHighValueOrders(500, ['credit_card', 'paypal']) const analytics = await getOrderAnalytics({ start: new Date('2024-01-01'), end: new Date('2024-12-31') }) ``` -------------------------------- ### MongoDB Local Development Connection URI Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/installation.mdx This URI format is used for connecting to a MongoDB instance running locally on the default port 27017, targeting the 'myapp' database. It's suitable for basic local development setups without authentication. ```plaintext mongodb://localhost:27017/myapp ``` -------------------------------- ### Building the Documentation Site (Bash) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/DEPLOYMENT.md Executes the build script defined in `package.json` for the documentation site. This command compiles the source files into static assets, typically outputting them to a `dist` directory. ```bash npm run build ``` -------------------------------- ### Example Usage of Nearby Location Search (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/advanced-queries.mdx Demonstrates how to call the `findNearbyLocations` function with specific parameters, such as user coordinates, max distance, type, minimum rating, and price range. It then logs the count and details of the found restaurants, including their distance and rating. ```typescript const nearbyRestaurants = await findNearbyLocations( { lat: 40.7589, lng: -73.9851 }, // Times Square, NYC { maxDistance: 2000, // 2km type: 'restaurant', minRating: 4.0, priceRange: ['$$', '$$$'], limit: 20 } ) console.log('Found restaurants:', nearbyRestaurants.length) nearbyRestaurants.forEach(restaurant => { console.log(`${restaurant.name} - ${restaurant.distanceKm}km away, ${restaurant.rating}⭐`) }) ``` -------------------------------- ### Advanced Aggregation Pipelines in Adonis-ODM (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx Provides examples of complex aggregation pipelines using the `aggregate` method, including grouping by fields, calculating statistics like sum, average, min, and max, and sorting aggregated results. It also demonstrates grouping by date components for time-series analysis. ```typescript // User statistics const userStats = await User.query() .aggregate([ { $group: { _id: '$role', count: { $sum: 1 }, avgAge: { $avg: '$age' }, minAge: { $min: '$age' }, maxAge: { $max: '$age' } } }, { $sort: { count: -1 } } ]) console.log('User statistics by role:', userStats) // Monthly user registration const monthlyRegistrations = await User.query() .aggregate([ { $group: { _id: { year: { $year: '$createdAt' }, month: { $month: '$createdAt' } }, count: { $sum: 1 } } }, { $sort: { '_id.year': -1, '_id.month': -1 } } ]) ``` -------------------------------- ### Invoking and Displaying Content Analytics Results in TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/advanced-queries.mdx This code snippet demonstrates how to call the `getContentAnalytics` function with a defined start and end date. After awaiting the results, it iterates through the returned array of author performance statistics and logs a summary for each author, including their name, post count, and total views, to the console. ```typescript // Usage const contentAnalytics = await getContentAnalytics({ start: new Date('2024-01-01'), end: new Date('2024-12-31') }) contentAnalytics.forEach(author => { console.log(`${author.authorName}: ${author.postCount} posts, ${author.totalViews} views`) }) ``` -------------------------------- ### Sorting and Limiting Query Results in Adonis-ODM (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx Illustrates how to order query results by single or multiple fields using `orderBy` and how to limit the number of results using `limit`. It also shows an example of pagination using the `paginate` method to retrieve data in chunks. ```typescript // Order by single field const recentUsers = await User.query() .orderBy('createdAt', 'desc') .limit(10) .all() // Order by multiple fields const sortedUsers = await User.query() .orderBy('status', 'asc') .orderBy('createdAt', 'desc') .all() // Pagination const page = 1 const perPage = 20 const paginatedUsers = await User.query() .where('status', 'active') .orderBy('createdAt', 'desc') .paginate(page, perPage) console.log('Users:', paginatedUsers.data) console.log('Total:', paginatedUsers.meta.total) console.log('Current page:', paginatedUsers.meta.page) ``` -------------------------------- ### Example of Creating a User in Adonis ODM Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/base-model.mdx This example illustrates how to use the `create` method to add a new user document to the database. It demonstrates passing an object of attributes to the method, which then returns the newly created `User` instance. ```typescript const user = await User.create({ name: 'John Doe', email: 'john@example.com' }) ``` -------------------------------- ### Testing Adonis ODM MongoDB Connection Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/installation.mdx This TypeScript code snippet provides an example of how to test the MongoDB connection established by Adonis ODM. It imports the `db` service, retrieves the client and database instances, and performs a simple `ping` operation on the database admin to confirm successful connectivity. The function returns a status indicating success or failure. ```typescript // In a controller or route import db from "adonis-odm/services/db"; export default class TestController { async testConnection() { try { // Test the connection const client = db.connection(); const database = db.db(); // Simple ping test await database.admin().ping(); return { status: "Connected to MongoDB successfully!" }; } catch (error) { return { status: "Connection failed", error: error.message }; } } } ``` -------------------------------- ### Installing adonis-odm with pnpm Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/README.md This command installs the `adonis-odm` package using pnpm, adding it as a dependency to your project. pnpm is a fast, disk-space efficient package manager. ```bash pnpm add adonis-odm ``` -------------------------------- ### Installing Project Dependencies - npm Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/README.md This command installs all necessary Node.js package dependencies defined in the `package.json` file, which are required for the project to run and build correctly. ```bash npm install ``` -------------------------------- ### Examples: OR Where Clauses (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/query-builder.mdx These examples illustrate various ways to use `orWhere` to combine conditions, including simple OR, OR with an operator, and OR with a nested callback for complex logical grouping. ```typescript // Simple OR await User.query() .where('role', 'admin') .orWhere('role', 'moderator') .all() // OR with operator await User.query() .where('age', '>', 65) .orWhere('status', '=', 'premium') .all() // OR with callback await User.query() .where('status', 'active') .orWhere((query) => { query.where('role', 'admin').where('isVerified', true) }) .all() ``` -------------------------------- ### Configuring Adonis ODM Package (Bash) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/commands.mdx This command configures the Adonis ODM package after installation, setting up necessary files and configurations for its operation within an AdonisJS project. ```bash node ace configure adonis-odm ``` -------------------------------- ### Installing adonis-odm with Yarn Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/README.md This command installs the `adonis-odm` package using Yarn, adding it as a dependency to your project. It's an alternative to npm for package management. ```bash yarn add adonis-odm ``` -------------------------------- ### Installing adonis-odm with npm Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/README.md This command installs the `adonis-odm` package using npm, adding it as a dependency to your project. It's the standard way to include the ODM in an AdonisJS application. ```bash npm i adonis-odm ``` -------------------------------- ### Example: Filling User Model Attributes - TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/base-model.mdx Illustrates how to use the `fill()` method to assign multiple attributes to a new `User` instance in a single operation. This is a convenient way to initialize model data. ```typescript const user = new User() user.fill({ name: 'John Doe', email: 'john@example.com' }) ``` -------------------------------- ### Example Adonis ODM Custom Sync Command (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/commands.mdx This TypeScript example demonstrates a custom Adonis Ace command (`sync:users`) that extends `BaseCommand`. It includes logic to fetch users from an external API and use `User.updateOrCreate` to synchronize them with the MongoDB database, showcasing error handling and logging. ```typescript 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 [] } } ``` -------------------------------- ### Example: Implementing Model Lifecycle Hooks - TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/base-model.mdx Illustrates how to implement `@beforeSave()` and `@beforeCreate()` hooks within an Adonis ODM model. The example shows normalizing email addresses before saving and hashing passwords before creating a new user. ```typescript export default class User extends BaseModel { @column() declare email: string @column() declare password: string @beforeSave() static async normalizeEmail(user: User) { if (user.$dirty.email) { user.email = user.email.toLowerCase().trim() } } @beforeCreate() static async hashPassword(user: User) { if (user.password) { user.password = await Hash.make(user.password) } } } ``` -------------------------------- ### Example of Updating or Creating a User in Adonis ODM Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/base-model.mdx This example demonstrates how to use the `updateOrCreate` method to either update an existing user (identified by email) or create a new one if the email doesn't exist. It showcases how to provide both search criteria and the attributes to be applied or used for creation. ```typescript const user = await User.updateOrCreate( { email: 'john@example.com' }, { name: 'John Doe', isActive: true } ) ``` -------------------------------- ### Example of Creating Multiple Users in Adonis ODM Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/base-model.mdx This example demonstrates how to use the `createMany` method to efficiently insert multiple user documents into the database. It takes an array of attribute objects, allowing for batch creation of model instances. ```typescript const users = await User.createMany([ { name: 'John', email: 'john@example.com' }, { name: 'Jane', email: 'jane@example.com' } ]) ``` -------------------------------- ### Example: Basic CRUD Operations with Adonis ODM - TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/base-model.mdx Provides a comprehensive example demonstrating fundamental Create, Read, Update, and Delete (CRUD) operations using an Adonis ODM model. It covers `create`, `find`, `findBy`, `save`, and `delete` methods. ```typescript // Create const user = await User.create({ name: 'John Doe', email: 'john@example.com' }) // Read const foundUser = await User.find(user._id) const userByEmail = await User.findBy('email', 'john@example.com') // Update user.name = 'John Smith' await user.save() // Delete await user.delete() ``` -------------------------------- ### Getting Database Connections - JavaScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/database-manager.mdx Demonstrates how to obtain default and named database connections using `Database.connection()` and then use a retrieved connection to perform a simple `find` query on a collection. ```javascript import Database from '@ioc:Adonis/Lucid/Database' // Get default connection const defaultConnection = Database.connection() // Get named connection const analyticsConnection = Database.connection('analytics') const logsConnection = Database.connection('logs') // Use connection for queries const users = await defaultConnection .collection('users') .find({ status: 'active' }) .toArray() ``` -------------------------------- ### MongoDB Replica Set Connection URI Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/installation.mdx This URI specifies multiple hosts for connecting to a MongoDB replica set, along with the `replicaSet` option. It ensures high availability and is required for transaction support in MongoDB. ```plaintext mongodb://host1:27017,host2:27017,host3:27017/myapp?replicaSet=myReplicaSet ``` -------------------------------- ### Configuring Adonis ODM Package Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/README.md This Bash command is essential for setting up the `adonis-odm` package after installation. Running `node ace configure adonis-odm` integrates the ODM into your AdonisJS project, preparing it for database operations. ```bash node ace configure adonis-odm ``` -------------------------------- ### Authenticating Wrangler with Cloudflare (Bash) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/DEPLOYMENT.md Authenticates the Wrangler CLI with your Cloudflare account. This command opens a browser window for you to log in and grant necessary permissions, allowing Wrangler to manage your Cloudflare resources. ```bash wrangler login ``` -------------------------------- ### Example: Saving a New User Model - TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/base-model.mdx Demonstrates how to create a new `User` instance, assign values to its properties, and then save it to the database using the `save()` method. This operation persists the new record. ```typescript const user = new User() user.name = 'John Doe' user.email = 'john@example.com' await user.save() ``` -------------------------------- ### Creating Query Instances in Adonis ODM (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/query-builder.mdx This snippet demonstrates how to initialize a query builder instance by calling the `query()` method on any model. It also shows a basic example of executing a query to retrieve all documents. ```TypeScript import User from '#models/user' // Create a query builder instance const query = User.query() // Execute the query const users = await User.query().all() ``` -------------------------------- ### MongoDB Authenticated Connection URI Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/installation.mdx This URI includes a username and password for connecting to a MongoDB instance, ensuring secure access to the 'myapp' database on localhost. It's essential when your MongoDB deployment requires authentication. ```plaintext mongodb://username:password@localhost:27017/myapp ``` -------------------------------- ### Integrating Pagefind into Build Scripts (JSON) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/search.mdx This JSON snippet illustrates how Pagefind search indexing is integrated into the project's `package.json` build scripts. It defines a `build` script that includes the Pagefind command to generate the search index after the main Astro build, and a dedicated `build:search` script for rebuilding only the search index. ```JSON { "scripts": { "build": "astro check && astro build && npx pagefind --site dist", "build:search": "npx pagefind --site dist" } } ``` -------------------------------- ### MongoDB Transaction Not Supported Error Message Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/installation.mdx This error indicates that the current MongoDB deployment does not support transactions, usually because it's a standalone instance rather than a replica set or sharded cluster. A replica set setup is required for transactions. ```plaintext Error: Transactions are not supported by this deployment ``` -------------------------------- ### MongoDB Atlas Connection URI Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/installation.mdx This URI uses the `mongodb+srv` protocol for connecting to a MongoDB Atlas cluster. It includes authentication credentials and the cluster hostname, simplifying connections to cloud-hosted MongoDB services. ```plaintext mongodb+srv://username:password@cluster.mongodb.net/myapp ``` -------------------------------- ### Using Regular Expressions for Embedded Queries in Adonis ODM (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/embedded-documents.mdx Shows how to use regular expressions to query embedded document fields for pattern matching. This example finds users whose zip code starts with '100'. ```TypeScript // Regular expressions const users = await User.query() .where('address.zipCode', 'regex', /^100/) .all() ``` -------------------------------- ### Testing Database Connections on Application Startup (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/connections.mdx This `DatabaseProvider` class demonstrates how to verify the establishment of multiple database connections (e.g., 'primary', 'analytics', 'logs') during application startup. It uses a `rawQuery` to ping each connection, logging success or failure and throwing an error if any connection fails. ```typescript // start/database.ts import Database from '@ioc:Adonis/Lucid/Database' export default class DatabaseProvider { public async ready() { // Test all connections on startup const connections = ['primary', 'analytics', 'logs'] for (const connectionName of connections) { try { await Database.connection(connectionName).rawQuery({ ping: 1 }) console.log(`✅ ${connectionName} connection established`) } catch (error) { console.error(`❌ ${connectionName} connection failed:`, error.message) throw error } } } public async shutdown() { // Gracefully close all connections const connections = ['primary', 'analytics', 'logs'] for (const connectionName of connections) { try { await Database.connection(connectionName).disconnect() console.log(`🔌 ${connectionName} connection closed`) } catch (error) { console.error(`Error closing ${connectionName}:`, error.message) } } } } ``` -------------------------------- ### Handling Common Errors in Adonis-ODM Operations (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx Covers error handling patterns for common database-related issues such as `E_ROW_NOT_FOUND` when a record is not found, `E_VALIDATION_FAILURE` for validation errors during model creation, and `11000` for MongoDB duplicate key errors. ```typescript // Handle not found errors try { const user = await User.findOrFail('invalid-id') } catch (error) { if (error.code === 'E_ROW_NOT_FOUND') { console.log('User not found') // Handle gracefully } else { throw error } } // Handle validation errors try { const user = await User.create({ email: 'invalid-email' // This might fail validation }) } catch (error) { if (error.code === 'E_VALIDATION_FAILURE') { console.log('Validation errors:', error.messages) } else { throw error } } // Handle duplicate key errors try { const user = await User.create({ email: 'existing@example.com' // Email already exists }) } catch (error) { if (error.code === 11000) { // MongoDB duplicate key error console.log('Email already exists') } else { throw error } } ``` -------------------------------- ### Performing Simple Queries in Adonis ODM (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/query-builder.mdx This section illustrates fundamental query operations. It includes examples for retrieving all documents, fetching the first document, finding a document by its ID, and counting the total number of documents in a collection. ```TypeScript // Find all users const allUsers = await User.query().all() // Find first user const firstUser = await User.query().first() // Find user by ID const user = await User.query().find('507f1f77bcf86cd799439011') // Count documents const userCount = await User.query().count() ``` -------------------------------- ### Configuring Pagefind for Search Indexing (YAML) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/search.mdx This YAML configuration snippet details the settings for Pagefind, which powers the documentation's search functionality. It specifies the output directory for the search index, defines root selectors for content to be indexed, and lists selectors to exclude, ensuring only relevant documentation content is searchable. ```YAML # Pagefind Configuration site: dist output_subdir: pagefind root_selector: "main, [data-pagefind-body]" exclude_selectors: - "nav" - "header" - "footer" - ".sidebar" force_language: "en" verbose: true ``` -------------------------------- ### Creating Blog Posts with Adonis ODM (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx This function creates a new blog post, verifying the author's existence using `User.findOrFail()` and generating a URL-friendly slug. It then uses `Post.create()` to persist the post, including handling tags and publication status. ```typescript async function createBlogPost(authorId: string, postData: { title: string content: string tags: string[] publish: boolean }) { try { // Verify author exists const author = await User.findOrFail(authorId) // Generate slug from title const slug = postData.title .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-|-$/g, '') // Create post const post = await Post.create({ title: postData.title, content: postData.content, slug, authorId: author._id, isPublished: postData.publish, tags: postData.tags, viewCount: 0, publishedAt: postData.publish ? DateTime.now() : null }) console.log('Post created:', post.title) return post } catch (error) { console.error('Failed to create post:', error.message) throw error } } // Usage const newPost = await createBlogPost('507f1f77bcf86cd799439011', { title: 'Getting Started with Adonis ODM', content: 'In this post, we will explore...', tags: ['adonis', 'mongodb', 'tutorial'], publish: true }) ``` -------------------------------- ### Deploying Site to Cloudflare Pages via Wrangler (Bash) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/DEPLOYMENT.md Deploys the built static assets from the `dist` directory to Cloudflare Pages using the Wrangler CLI. The `--project-name` flag specifies the name of the Cloudflare Pages project for this deployment. ```bash wrangler pages deploy dist --project-name adonis-odm-docs ``` -------------------------------- ### Registering Users with Adonis ODM (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx This function handles user registration, including checking for existing emails and creating a new user with default status and role. It uses `User.query().where().first()` for lookup and `User.create()` for insertion, throwing an error if the email is already registered. ```typescript async function registerUser(userData: { name: string email: string password: string age: number }) { try { // Check if email already exists const existingUser = await User.query() .where('email', userData.email) .first() if (existingUser) { throw new Error('Email already registered') } // Create new user const user = await User.create({ ...userData, status: 'pending', role: 'user' }) console.log('User registered successfully:', user._id) return user } catch (error) { console.error('Registration failed:', error.message) throw error } } // Usage const newUser = await registerUser({ name: 'Jane Doe', email: 'jane@example.com', password: 'hashedPassword', age: 25 }) ``` -------------------------------- ### Example: Filtering with WhereBetween (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/query-builder.mdx This example demonstrates using `whereBetween` to retrieve `User` documents whose `age` is between 18 and 65, inclusive. ```typescript await User.query() .whereBetween('age', [18, 65]) .all() ``` -------------------------------- ### Example: Filtering with WhereIn (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/query-builder.mdx This example demonstrates using `whereIn` to retrieve `User` documents whose `role` is one of 'admin', 'moderator', or 'editor'. ```typescript await User.query() .whereIn('role', ['admin', 'moderator', 'editor']) .all() ``` -------------------------------- ### Generating Various Adonis ODM Models (Bash) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/commands.mdx This example showcases generating multiple Adonis ODM models for different application domains like user management, blogging, and analytics. It demonstrates the use of `--exact` and `--connection` flags for specific naming and database configurations. ```bash # 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 ``` -------------------------------- ### Example: Basic Where Clause (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/query-builder.mdx This example demonstrates using the `where` method to filter `User` documents where the `status` field is 'active', then retrieves all matching users. ```typescript const users = await User.query() .where('status', 'active') .all() ``` -------------------------------- ### Configuring Adonis ODM Package using Ace Command Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/installation.mdx This command initiates the configuration process for Adonis ODM within an AdonisJS v6 project. It automatically registers the MongoDB provider, creates the `config/odm.ts` file, adds necessary environment variables to `.env`, and sets up validation rules for these variables. ```bash node ace configure adonis-odm ``` -------------------------------- ### Creating Single and Multiple Records with Adonis ODM - TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx Demonstrates how to create new records using Adonis ODM. It shows creating a single 'User' instance with 'User.create()' and creating multiple 'User' instances using 'User.createMany()', logging the IDs of the created records. ```typescript // Create a single user const user = await User.create({ name: 'John Doe', email: 'john@example.com', password: 'hashedPassword', age: 30, status: 'active', role: 'user' }) console.log('Created user:', user._id) // Create multiple users const users = await User.createMany([ { name: 'Alice Smith', email: 'alice@example.com', password: 'hashedPassword', age: 28, status: 'active', role: 'user' }, { name: 'Bob Johnson', email: 'bob@example.com', password: 'hashedPassword', age: 35, status: 'pending', role: 'moderator' } ]) console.log(`Created ${users.length} users`) ``` -------------------------------- ### Building Adonis ODM Site with Search Index Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/README.md These Bash commands are used to build the documentation site and manage its search index, which is powered by Pagefind. `npm run build` compiles the site and generates the search index, while `npm run build:search` specifically regenerates only the search index. ```bash npm run build # Builds site and generates search index npm run build:search # Regenerates search index only ``` -------------------------------- ### Example: Grouped Where Clause (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/query-builder.mdx This example demonstrates using a callback to group `orWhere` conditions within a `where` clause, filtering active users who are either 'admin' or 'moderator'. ```typescript const users = await User.query() .where('status', 'active') .where((query) => { query.where('role', 'admin').orWhere('role', 'moderator') }) .all() ``` -------------------------------- ### Reading Records with Adonis ODM Queries - TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx Illustrates various methods for reading records using Adonis ODM. It covers finding all records, finding by ID ('find', 'findOrFail'), finding the first matching record, finding all matching records, querying with 'whereIn', and querying with 'whereBetween' for range-based searches. ```typescript // Find all users const allUsers = await User.query().all() // Find user by ID const user = await User.find('507f1f77bcf86cd799439011') if (user) { console.log('Found user:', user.name) } // Find user by ID or throw error const userOrFail = await User.findOrFail('507f1f77bcf86cd799439011') // Find first user matching criteria const activeUser = await User.query() .where('status', 'active') .first() // Find all active users const activeUsers = await User.query() .where('status', 'active') .all() // Find users with specific roles const admins = await User.query() .whereIn('role', ['admin', 'moderator']) .all() // Find users by age range const adults = await User.query() .whereBetween('age', [18, 65]) .all() ``` -------------------------------- ### Querying and Preloading Relationships in Adonis-ODM (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx Demonstrates how to preload related data using `preload` to efficiently fetch associated models and avoid N+1 query issues. It also shows how to filter parent records based on conditions in their related models using `whereHas`. ```typescript // Preload author information const postsWithAuthors = await Post.query() .preload('author', (query) => { query.select('name', 'email') }) .where('isPublished', true) .all() // Access preloaded data postsWithAuthors.forEach(post => { console.log(`${post.title} by ${post.author.name}`) }) // Query posts by author const johnsPosts = await Post.query() .whereHas('author', (query) => { query.where('name', 'like', '%John%') }) .all() ``` -------------------------------- ### Example of Querying Users in Adonis ODM Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/base-model.mdx This example demonstrates how to use the `query` method to retrieve all users where the `isActive` field is true. It showcases chaining `where` and `all` methods on the `ModelQueryBuilder` to filter and fetch documents. ```typescript const users = await User.query().where('isActive', true).all() ``` -------------------------------- ### Defining User Model with Adonis ODM - TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx Defines the 'User' model using Adonis ODM's 'BaseModel'. It includes various columns like '_id', 'name', 'email', 'password', 'age', 'status', 'role', 'createdAt', and 'updatedAt', demonstrating primary key, basic types, enums, and auto-timestamping. ```typescript // app/models/user.ts import { BaseModel, column } from 'adonis-odm' import { DateTime } from 'luxon' export default class User extends BaseModel { @column({ isPrimary: true }) declare _id: string @column() declare name: string @column() declare email: string @column() declare password: string @column() declare age: number @column() declare status: 'active' | 'inactive' | 'pending' @column() declare role: 'user' | 'admin' | 'moderator' @column.dateTime({ autoCreate: true }) declare createdAt: DateTime @column.dateTime({ autoCreate: true, autoUpdate: true }) declare updatedAt: DateTime } ``` -------------------------------- ### Managing Test Data with Setup Hooks and Factories in TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/testing.mdx This snippet illustrates effective test data management strategies. It shows how to use group.each.setup to clean up database records before each test, ensuring a consistent state. Additionally, it demonstrates the use of ModelFactory for creating consistent and reusable test data. ```typescript // Good: Clean up after each test group.each.setup(async () => { await User.query().delete() }) // Good: Use factories for consistent test data const user = await ModelFactory.createUser({ age: 30 }) ``` -------------------------------- ### Example of Finding a User by Email in Adonis ODM Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/base-model.mdx This example demonstrates how to use the `findBy` method to retrieve a user document by a specific field, in this case, the `email` address. It returns the `User` instance if a match is found, or `null` otherwise. ```typescript const user = await User.findBy('email', 'john@example.com') ``` -------------------------------- ### Registering Adonis ODM Provider in adonisrc.ts Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/installation.mdx This snippet demonstrates how to verify that the Adonis ODM provider is correctly registered in the `adonisrc.ts` file. The `() => import("adonis-odm/provider")` entry ensures that Adonis ODM's services and functionalities are loaded and available within the AdonisJS application. ```typescript { providers: [ // ... other providers () => import("adonis-odm/provider") ]; } ``` -------------------------------- ### Implementing Singleton Pattern for App Settings in TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/embedded-documents.mdx This static asynchronous method implements a singleton pattern for the AppSettings model. It attempts to retrieve the existing settings document; if none is found, it creates a new one with default values, ensuring that only one settings document ever exists in the database. ```TypeScript // Singleton pattern - only one settings document static async getInstance() { let settings = await this.query().first() if (!settings) { settings = await this.create({ siteName: 'My Application', siteDescription: 'A great application built with Adonis ODM', siteUrl: 'https://example.com', adminEmail: 'admin@example.com', timezone: 'UTC', language: 'en', features: { enableComments: true, enableRegistration: true, enableSocialLogin: false, enablePayments: false, maintenanceMode: false }, email: { provider: 'smtp', fromEmail: 'noreply@example.com', fromName: 'My Application', replyToEmail: 'support@example.com' }, payments: { enabledProviders: [], defaultCurrency: 'USD', taxRate: 0.08, freeShippingThreshold: 100 } }) } return settings } } ``` -------------------------------- ### Checking Embedded Document Existence with whereEmbeddedExists (JavaScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/embedded-query-builder.mdx These examples illustrate the use of `whereEmbeddedExists` to find documents where a specific embedded field is present. The first example finds users with an 'address' field, and the second finds companies with 'headquarters.contact' information. ```typescript // Find users with address information const users = await User.query() .whereEmbeddedExists('address') .all() // Find companies with headquarters contact info const companies = await Company.query() .whereEmbeddedExists('headquarters.contact') .all() ``` -------------------------------- ### Example of Finding a User by ID in Adonis ODM Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/base-model.mdx This example demonstrates how to use the `find` method to retrieve a user document by its unique primary key (ID). The method returns the `User` instance if found, or `null` if no matching document exists. ```typescript const user = await User.find('507f1f77bcf86cd799439011') ``` -------------------------------- ### Building and Publishing Package - npm Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/README.md This command sequence first compiles the project's source code and then publishes the compiled package to the npm registry, making it available for public use and distribution. ```bash npm run compile npm publish ``` -------------------------------- ### Querying Users with Lucid-style Syntax (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/introduction.mdx This snippet demonstrates how to query users using a familiar Lucid ORM-like syntax in Adonis ODM. It filters users by age and email, orders them, and paginates the results, showcasing the fluent query builder's capabilities. ```typescript // Query with familiar Lucid syntax const users = await User.query() .where("age", ">=", 18) .where("email", "like", "%@gmail.com") .orderBy("createdAt", "desc") .paginate(1, 10); ``` -------------------------------- ### Examples: Where Clauses with Operators (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/query-builder.mdx These examples showcase various `where` clauses using different comparison, pattern matching, array, range, and existence operators to filter `User` documents based on age, status, email, role, score, and profile picture. ```typescript // Comparison operators await User.query().where('age', '>', 18).all() await User.query().where('age', '>=', 21).all() await User.query().where('status', '!=', 'banned').all() // Pattern matching await User.query().where('email', 'like', '%@gmail.com').all() await User.query().where('name', 'ilike', 'john%').all() // Array operations await User.query().where('role', 'in', ['admin', 'moderator']).all() await User.query().where('status', 'not in', ['banned', 'suspended']).all() // Range operations await User.query().where('age', 'between', [18, 65]).all() await User.query().where('score', 'not between', [0, 50]).all() // Existence checks await User.query().where('profilePicture', 'exists').all() await User.query().where('deletedAt', 'not exists').all() // Null checks await User.query().where('deletedAt', 'null').all() await User.query().where('email', 'not null').all() ``` -------------------------------- ### Searching and Filtering Blog Posts with Adonis ODM (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/basic-usage.mdx This function provides advanced search and filtering capabilities for blog posts, supporting text search across title/content, filtering by author, tags, and publication status. It also preloads author information and implements pagination using `query.paginate()`. ```typescript async function searchPosts(filters: { query?: string author?: string tags?: string[] published?: boolean page?: number perPage?: number }) { const query = Post.query() // Text search if (filters.query) { query.where((subQuery) => { subQuery .where('title', 'like', `%${filters.query}%`) .orWhere('content', 'like', `%${filters.query}%`) }) } // Filter by author if (filters.author) { query.whereHas('author', (authorQuery) => { authorQuery.where('name', 'like', `%${filters.author}%`) }) } // Filter by tags if (filters.tags && filters.tags.length > 0) { query.whereArrayContainsAny('tags', filters.tags) } // Filter by published status if (filters.published !== undefined) { query.where('isPublished', filters.published) } // Preload author query.preload('author', (authorQuery) => { authorQuery.select('name', 'email') }) // Sort by most recent query.orderBy('createdAt', 'desc') // Paginate const page = filters.page || 1 const perPage = filters.perPage || 10 return await query.paginate(page, perPage) } // Usage const searchResults = await searchPosts({ query: 'mongodb', tags: ['tutorial'], published: true, page: 1, perPage: 20 }) console.log('Found posts:', searchResults.data.length) console.log('Total posts:', searchResults.meta.total) ``` -------------------------------- ### Querying Specific Array Elements with whereArrayElement (JavaScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/api/embedded-query-builder.mdx These examples illustrate how to use `whereArrayElement` to query a specific element in an array by its index. The first example finds users where the first tag is 'premium', and the second finds orders where the second item has a specific product ID. ```typescript // Find users where first tag is 'premium' const users = await User.query() .whereArrayElement('tags', 0, 'premium') .all() // Find orders where second item has specific product ID const orders = await Order.query() .whereArrayElement('items', 1, { productId: 'prod123' }) .all() ``` -------------------------------- ### Batch Creating Users with Error Handling in TypeScript Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/examples/advanced-queries.mdx This asynchronous function creates multiple user records in batches, providing robust error handling. It processes users in chunks using `User.createMany` and falls back to individual `User.create` for failed batches to identify and log problematic records, ensuring partial success. ```TypeScript // Batch create with validation async function batchCreateUsers(usersData: any[], batchSize: number = 100) { const results = [] // Process in batches to avoid memory issues for (let i = 0; i < usersData.length; i += batchSize) { const batch = usersData.slice(i, i + batchSize) try { const batchResults = await User.createMany(batch) results.push(...batchResults) console.log(`Processed batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(usersData.length / batchSize)}`) } catch (error) { console.error(`Batch ${Math.floor(i / batchSize) + 1} failed:`, error.message) // Process individually to identify problematic records for (const userData of batch) { try { const user = await User.create(userData) results.push(user) } catch (individualError) { console.error(`Failed to create user ${userData.email}:`, individualError.message) } } } } return results } ``` -------------------------------- ### Performing ACID Transactions (TypeScript) Source: https://github.com/dreamshive/adonis-odm.dreamshive.io/blob/main/src/pages/docs/introduction.mdx This example demonstrates how to perform ACID transactions using Adonis ODM's `db.transaction` method. It shows creating a user and a profile within a single, atomic operation, ensuring data consistency across multiple model operations. ```typescript import db from "adonis-odm/services/db"; // Managed transaction (recommended) const result = await db.transaction(async (trx) => { const user = await User.create( { name: "John Doe", email: "john@example.com", }, { client: trx } ); const profile = await Profile.create( { userId: user._id, firstName: "John", lastName: "Doe", }, { client: trx } ); return { user, profile }; }); ```