简体   繁体   中英

Writing raw JSON to CosmosDB and an Azure Function

I want to take the raw JSON body from an HTTP post and write it directly into my CosmosDB.

Let's say the data looks like this:

{
  "id": "123456",
  "storeName": "City Bar and Grille",
  "invoiceTotal": 65
}

However, the documentsOut.AddAsync command uses a format like this:

wait documentsOut.AddAsync(new
  {
    // create a random ID
    id = System.Guid.NewGuid().ToString(),
    body = sourceJson
  });

And then I end up with a document that looks like this:

{
  "id": "0e99d3ab-1956-4c0a-8ec1-99de5c987555",
  "body": {
    "id": "123456",
    "storeName": "City Bar and Grille",
    "invoiceTotal": 65
  }
}

What I really want is to end up with this:

{
  "id": "123456",
  "storeName": "City Bar and Grille",
  "invoiceTotal": 65
}

I'd like to drop the id = System.Guid.NewGuid().ToString() completely (which should not be hard).

How can I pass the raw JSON through without needing to add it to some parent node (such as body)?

Using a similar example as shared by you in the question. We can create a Model class with properties which want to store in database.

在此处输入图像描述

public class StoreDetails : TableEntity
{
    [JsonProperty("id")]
    public string Id { get; set; } 
    [JsonProperty("storeName")]
    public string StoreName { get; set; }
    [JsonProperty("invoiceTotal")]
    public string InvoiceTotal { get; set; }
}

Then can create object of model and pass that object to AddAsync() method. As shown in below screenshot.

在此处输入图像描述

        var item = new StoreDetails
        {
            Id = Guid.NewGuid().ToString(),
            StoreName = data.StoreName,
            InvoiceTotal = data.InvoiceTotal
        };
        await storeDetailOut.AddAsync(item);

and when we triggered post API, got response as shown below.

在此处输入图像描述

As finally we can see the same record is stored in CosmosDB.

在此处输入图像描述

Just to formalize my comment as an answer: You're specifically creating the body property of the Cosmos DB document you're creating:

wait documentsOut.AddAsync(new
  {
    // create a random ID
    id = System.Guid.NewGuid().ToString(),
    body = sourceJson
  });

At the same time, you're ignoring the incoming ID. Since you wanted to preserve that ID, You can copy the ID over (as long as it remains unique within the partition) instead of generating a new GUID, and also grab individual properties from sourceJson to avoid the nested body element:

wait documentsOut.AddAsync(new
  {
    id = sourceJson.id,
    storeName = sourceJson.storeName,
    invoiceTotal = sourceJson.invoiceTotal
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM