> ## Documentation Index
> Fetch the complete documentation index at: https://www.orionjs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Collections

> Creating and configuring MongoDB collections in Orionjs

Collections in Orionjs provide a type-safe interface to MongoDB collections with automatic schema validation and helpful query methods.

## Creating Collections

There are two main ways to create collections in Orionjs:

### Using the Repository Pattern (Recommended)

The recommended approach is to use the repository pattern with proper typing:

```typescript theme={null}
import {Repository} from '@orion-js/services'
import {createCollection, typedId, OptionalId} from '@orion-js/mongodb'
import {schemaWithName, InferSchemaType} from '@orion-js/schema'

const UserSchema = schemaWithName('UserSchema', {
  _id: {type: typedId('user')},
  name: {type: String},
  email: {type: String, optional: true}
})

type UserType = InferSchemaType<typeof UserSchema>

@Repository()
export class UserRepository {
  users = createCollection({
    name: 'users',
    schema: UserSchema,
    // Other options...
  })
  
  async findByEmail(email: string): Promise<UserType | null> {
    return await this.users.findOne({email})
  }
  
  async createUser(userData: OptionalId<UserType>): Promise<string> {
    return await this.users.insertOne(userData)
  }
}
```

### Using createCollection Directly

You can also create collections directly:

```typescript theme={null}
import {createCollection, typedId} from '@orion-js/mongodb'
import {schemaWithName, InferSchemaType} from '@orion-js/schema'

const UserSchema = schemaWithName('UserSchema', {
  _id: {type: typedId('user')},
  name: {type: String},
  email: {type: String, optional: true}
})

type UserType = InferSchemaType<typeof UserSchema>

const Users = createCollection({
  name: 'users',
  schema: UserSchema,
  // Other options...
})
```

## Configuration Options

The `createCollection` function accepts the following options:

```typescript theme={null}
{
  // Required options
  name: string,             // Collection name in MongoDB
  schema: SchemaType,       // Schema for validation and typing

  // Optional options
  connectionName: string,   // Connection name (default: 'main')
  idGeneration: 'mongo' | 'random' | 'uuid', // ID generation method (default: 'mongo')
  indexes: Index[],         // Array of indexes to create
} 
```

## ID Generation

Orionjs offers several options for generating document IDs:

```typescript theme={null}
const Users = createCollection({
  name: 'users',
  schema: UserSchema,
  idGeneration: 'uuid' // Generate UUIDs for _id
})
```

### Basic ID Generation Options

* `'mongo'` (default): MongoDB ObjectId strings (time-based)
* `'random'`: Random string IDs
* `'uuid'`: UUID v7 strings

### Typed IDs

For TypeScript users, Orionjs provides powerful ways to create type-safe IDs using `typedId`:

```typescript theme={null}
import {typedId} from '@orion-js/mongodb'
import {schemaWithName, InferSchemaType} from '@orion-js/schema'

const UserSchema = schemaWithName('UserSchema', {
  _id: {type: typedId('user')}, // Will create IDs like 'user-abc123'
  name: {type: String},
  email: {type: String}
})

type UserType = InferSchemaType<typeof UserSchema>
// UserType._id will be typed as `user-${string}`

const Users = createCollection({
  name: 'users',
  schema: UserSchema
})
```

The library will automatically detect `typedId` from the schema and use it to create prefixed IDs.

## Indexes

Define indexes to optimize queries:

```typescript theme={null}
const Users = createCollection({
  name: 'users',
  schema: UserSchema,
  indexes: [
    {
      keys: { email: 1 },
      options: { unique: true }
    },
    {
      keys: { createdAt: -1 }
    }
  ]
})
```

## Collection Types

When using TypeScript, properly type your collections:

```typescript theme={null}
// Infer type from schema
type UserType = InferSchemaType<typeof UserSchema>

// For document creation (without _id)
type NewUserType = OptionalId<UserType>
```

## Getting a Collection Instance

If you need to access a collection outside a repository:

```typescript theme={null}
import {getInstance} from '@orion-js/services'
import {UserRepository} from './UserRepository'

// Get the repository
const userRepo = getInstance(UserRepository)

// Use repository methods
const user = await userRepo.findByEmail('user@example.com')
```

Collections provide a solid foundation for working with MongoDB in Orionjs, with built-in type safety and schema validation to make your database operations more reliable.
