I have a model with _id, name and other fields. I want to create an index so it would be impossible to save documents with same names. I'm creating an index such way:
public static async Task EnsureIndexExists(this IMongoDatabase database, string collectionName, string indexName)
{
var collection = database.GetCollection<BsonDocument>(collectionName);
var builder = Builders<BsonDocument>.IndexKeys;
var field = new StringFieldDefinition<BsonDocument>(indexName.FromPascalToCamel());
var indexModel = new CreateIndexModel<BsonDocument>(builder.Ascending(field));
await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false);
}
// ...
database.EnsureIndexExists(CharacterRepository.CollectionName, nameof(CharacterEntity.Name)).Wait();
The model:
public class CharacterEntity
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
//...
}
But still documents with the same names can be saved into DB.
The driver versions:
<PackageReference Include="AspNetCore.Identity.MongoDbCore" Version="2.1.1" />
<PackageReference Include="MongoDB.Driver" Version="2.11.1" />
What I'm doing wrong?