Home > Enterprise >  ASP.NET MongoDb unstructured data exception
ASP.NET MongoDb unstructured data exception

Time:08-11

I struggle with C# ASP.NET sending (partially) unstructured data to MongoDb. How is it possible to add a field with unstructured data (unstructuredInfo) to a otherwise mapped class?

If not - how is BsonDocument or any other clever solution, anyway? I always get JsonExceptions with BsonDocuments.

Get Method works fine. I can't get it working for a Post Method. I get JsonExceptions.

... System.Text.Json.JsonException: The JSON value could not be converted to MongoDB.Bson.BsonDocument. ...

I setup a quick Github Repo with the test project. https://github.com/Maxoper/MongoDbProblem

public class Movie
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        public string Title { get; set; }
        public int Year { get; set; }
        public string Summary { get; set; } = null;
        public List<string> Actors { get; set; }

        [BsonExtraElements]
        public BsonDocument UnstructuredInfo { get; set; }
    }
public class MoviesService
    {
        private readonly IMongoCollection<Movie> _movies;

        public MoviesService(IOptions<MoviesDatabaseSettings> options)
        {
            var mongoClient = new MongoClient(options.Value.ConnectionString);

            _movies = mongoClient.GetDatabase(options.Value.DatabaseName)
                .GetCollection<Movie>(options.Value.MoviesCollectionName);
        }

        public async Task Create(Movie newMovie) =>
            await _movies.InsertOneAsync(newMovie);

app.MapPost("/api/movies", async (MoviesService moviesService, Movie movie) => 
{
  await moviesService.Create(movie);
    return Results.Ok();
});

CodePudding user response:

The problem is that the JSON cannot be converted to BsonDocument out of the box. Either you create a custom converter or you change the type of the property to IDictionary<string, object>:

[BsonExtraElements]
public IDictionary<string, object> UnstructuredInfo { get; set; }

This way, the JSON serializer does not have to deal with MongoDB specific classes like BsonDocument and you have better chances that everything can be serialized.

  • Related