Skip to content

Commit

Permalink
Add info on database setup for MongoDB
Browse files Browse the repository at this point in the history
  • Loading branch information
mburumaxwell committed Mar 7, 2024
1 parent 4f61ac7 commit 2ab2ca0
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
28 changes: 27 additions & 1 deletion samples/MongoDBSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,36 @@ class Person

class SampleDbContext(MongoDbContextOptions<SampleDbContext> options) : MongoDbContext(options)
{
public IMongoCollection<Person> Persons => Collection<Person>("Persons");
private const string ColNamePersons = "Persons";

public IMongoCollection<Person> Persons => Collection<Person>(ColNamePersons);

protected override void OnConfiguring(MongoDbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}

protected async override Task EnsureCreatedAsync(IMongoDatabase database, CancellationToken cancellationToken = default)
{
var names = await database.ListCollectionNames(null, cancellationToken).ToListAsync(cancellationToken);

if (!names.Contains(ColNamePersons, StringComparer.Ordinal))
{
var options = new CreateCollectionOptions<Person> { };
await database.CreateCollectionAsync(name: ColNamePersons,
options: options,
cancellationToken: cancellationToken);

// create indexes
await Persons.Indexes.CreateManyAsync(
models: [
// definition for Status
new CreateIndexModel<Person>(
Builders<Person>.IndexKeys.Ascending(p => p.Name),
new CreateIndexOptions<Person> { }),
],
cancellationToken: cancellationToken);
}

}
}
25 changes: 25 additions & 0 deletions src/Tingle.Extensions.MongoDB/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,31 @@ services.AddHealthChecks()
.AddMongoDbContextCheck<MyContext>();
```

## Database setup

For development and preview environments, databases may need to be created automatically on startup. This can be done using the `MONGO_CREATE_DATABASE` environment variable.

```json
{
"profiles": {
"SerilogSample": {
"commandName": "Project",
"dotnetRunMessages": true,
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development",
"MONGO_CREATE_DATABASE": "true"
}
}
}
}
```

In the application setup:

```cs
builder.Services.AddMongoDatabaseSetup<MyContext>(); // remember to override EnsureCreatedAsync(...) as per sample
```

## Extensions

A number of extensions for building indexes or performing operations on collections exist.
Expand Down

0 comments on commit 2ab2ca0

Please sign in to comment.