Skip to content

Instantly share code, notes, and snippets.

@robie2011
Last active August 20, 2020 06:09
Show Gist options
  • Save robie2011/7a145f59fb910afdbf9e94aad203a1dd to your computer and use it in GitHub Desktop.
Save robie2011/7a145f59fb910afdbf9e94aad203a1dd to your computer and use it in GitHub Desktop.
C# MongoDb get document by id not working
using MongoDB.Bson.Serialization.Conventions;
namespace Judasheet
{
public static class ConfigMongoDb
{
public static void SetupConvention()
{
var pack = new ConventionPack();
pack.Add(new CamelCaseElementNameConvention());
ConventionRegistry.Register(
"CamelCase",
pack, type => type.FullName.StartsWith("Judasheet.Models"));
}
}
}
using System;
using System.Linq;
using Judasheet;
using Judasheet.Models;
using MongoDB.Bson;
using MongoDB.Driver;
using Xunit;
namespace JudasheetTest
{
public class DbTest
{
private const string DatabaseName = "test";
private IMongoCollection<T>GetSongsCollection<T>(string collectionName = null)
{
ConfigMongoDb.SetupConvention();
var client = new MongoClient(Environment.GetEnvironmentVariable("TEST_JUDA_MONGODB_URI"));
var database = client.GetDatabase(DatabaseName);
var name = collectionName ?? typeof(T).Name.ToLower();
return database.GetCollection<T>(name);
}
[Fact]
public void ListAll_ResultNotEmpty()
{
var songs = GetSongsCollection<Song>().FindSync(_ => true).ToList();
Assert.NotEmpty(songs);
}
[Fact]
public void GetById_Workaround_NotNull()
{
var existingSong = GetSongsCollection<Song>().FindSync(_ => true).First();
var song = GetSongsCollection<Song>()
.AsQueryable()
.Single(s => s.Id.StartsWith(existingSong.Id));
}
// does not work!
[Fact]
public void GetById_NotNull()
{
var existingSong = GetSongsCollection<Song>().FindSync(_ => true).First();
var song = GetSongsCollection<Song>()
.Find(s => s.Id == existingSong.Id)
.Single();
}
[Fact]
public void GetByIdBson_NotNull()
{
var songs = GetSongsCollection<Song>();
var existingSong = songs.FindSync(_ => true).First();
var filters = Builders<BsonDocument>.Filter.Eq("_id", existingSong.Id);
GetSongsCollection<BsonDocument>("song").Find(filters).First();
}
}
}
using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace Judasheet.Models
{
public class Song
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public DateTime InsertDate { get; set; }
public DateTime UpdateDate { get; set; } = DateTime.Now;
public string Title { get; set; }
public string MainLanguage { get; set; }
public string SongType { get; set; }
public string SongWriter { get; set; }
public string Album { get; set; }
public List<Mastersheet> Mastersheets { get; set; }
public bool Verified { get; set; } = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment