Skip to content

json-api-dotnet/JsonApiDotNetCore.MongoDb

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MongoDB support for JsonApiDotNetCore

Build Coverage NuGet GitHub License

Plug-n-play implementation of IResourceRepository<TResource, TId>, allowing you to use MongoDB with your JsonApiDotNetCore API projects.

Getting started

The following steps describe how to create a JSON:API project with MongoDB.

  1. Install the JsonApiDotNetCore.MongoDb package:

    dotnet add package JsonApiDotNetCore.MongoDb
  2. Declare your entities, annotated with JsonApiDotNetCore attributes:

    #nullable enable
    
    [Resource]
    public class Person : HexStringMongoIdentifiable
    {
        [Attr] public string? FirstName { get; set; }
        [Attr] public string LastName { get; set; } = null!;
    }
  3. Configure MongoDB and JsonApiDotNetCore in Program.cs, seeding the database with sample data:

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddSingleton(_ =>
        new MongoClient("mongodb://localhost:27017").GetDatabase("ExampleDbName"));
    builder.Services.AddJsonApi(options =>
    {
        options.UseRelativeLinks = true;
        options.IncludeTotalResourceCount = true;
    }, resources: resourceGraphBuilder => resourceGraphBuilder.Add<Person, string?>());
    builder.Services.AddJsonApiMongoDb();
    builder.Services.AddResourceRepository<MongoRepository<Person, string?>>();
    
    var app = builder.Build();
    app.UseRouting();
    app.UseJsonApi();
    app.MapControllers();
    
    var database = app.Services.GetRequiredService<IMongoDatabase>();
    await CreateSampleDataAsync(database);
    
    app.Run();
    
    static async Task CreateSampleDataAsync(IMongoDatabase database)
    {
        await database.DropCollectionAsync(nameof(Person));
        await database.GetCollection<Person>(nameof(Person)).InsertManyAsync(new[]
        {
            new Person
            {
                FirstName = "John",
                LastName = "Doe",
            },
            new Person
            {
                FirstName = "Jane",
                LastName = "Doe",
            },
            new Person
            {
                FirstName = "John",
                LastName = "Smith",
            }
        });
    }
  4. Start your API

    dotnet run
  5. Send a GET request to retrieve data:

    GET http://localhost:5000/people?filter=equals(lastName,'Doe')&fields[people]=firstName HTTP/1.1
    Expand to view the JSON response
    {
      "links": {
        "self": "/people?filter=equals(lastName,%27Doe%27)&fields[people]=firstName",
        "first": "/people?filter=equals(lastName,%27Doe%27)&fields%5Bpeople%5D=firstName",
        "last": "/people?filter=equals(lastName,%27Doe%27)&fields%5Bpeople%5D=firstName"
      },
      "data": [
        {
          "type": "people",
          "id": "680cae2e1759666c5c1e988c",
          "attributes": {
            "firstName": "John"
          },
          "links": {
            "self": "/people/680cae2e1759666c5c1e988c"
          }
        },
        {
          "type": "people",
          "id": "680cae2e1759666c5c1e988d",
          "attributes": {
            "firstName": "Jane"
          },
          "links": {
            "self": "/people/680cae2e1759666c5c1e988d"
          }
        }
      ],
      "meta": {
        "total": 2
      }
    }

Tip

If your API project uses MongoDB only (so not in combination with EF Core), then instead of registering all MongoDB resources and repositories individually, you can use:

builder.Services.AddJsonApi(facade => facade.AddCurrentAssembly());
builder.Services.AddJsonApiMongoDb();

builder.Services.AddScoped(typeof(IResourceReadRepository<,>), typeof(MongoRepository<,>));
builder.Services.AddScoped(typeof(IResourceWriteRepository<,>), typeof(MongoRepository<,>));
builder.Services.AddScoped(typeof(IResourceRepository<,>), typeof(MongoRepository<,>));

Using client-generated IDs

Resources that inherit from HexStringMongoIdentifiable use auto-generated (high-performance) 12-byte hexadecimal Object IDs. You can assign an ID explicitly, but it must match the 12-byte hexadecimal pattern.

To use free-format string IDs, make your resources inherit from FreeStringMongoIdentifiable instead. When creating a resource without assigning an ID, a 12-byte hexadecimal ID will be auto-generated.

Set options.ClientIdGeneration to Allowed or Required from Program.cs to enable API clients to assign IDs. This can be combined with both base classes, but FreeStringMongoIdentifiable probably makes the most sense.

Limitations

  • JSON:API relationships are currently not supported. You can use complex object graphs though, which are stored in a single document.

Trying out the latest build

After each commit to the master branch, a new pre-release NuGet package is automatically published to feedz.io. To try it out, follow the steps below:

  1. Create a nuget.config file in the same directory as your .sln file, with the following contents:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <packageSources>
        <add key="json-api-dotnet" value="https://f.feedz.io/json-api-dotnet/jsonapidotnetcore/nuget/index.json" />
        <add key="NuGet" value="https://api.nuget.org/v3/index.json" />
      </packageSources>
    </configuration>
  2. In your IDE, browse the list of packages from the json-api-dotnet feed. Make sure pre-release packages are included in the list.

Contributing

Have a question, found a bug or want to submit code changes? See our contributing guidelines.

Build from source

To build the code from this repository locally, run:

dotnet build

You can run tests without MongoDB on your machine. The following command runs all tests:

dotnet test

A running instance of MongoDB is required to run the examples. If you have docker installed, you can launch MongoDB in a container with the following command:

pwsh run-docker-mongodb.ps1

And then to run the API:

dotnet run --project src/Examples/GettingStarted

Alternatively, to build, run all tests, generate code coverage and NuGet packages:

pwsh Build.ps1