[英]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.我想从 HTTP 帖子中获取原始 JSON 正文并将其直接写入我的 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:但是,documentsOut.AddAsync 命令使用如下格式:
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).我想完全删除 id = System.Guid.NewGuid().ToString() (这应该不难)。
How can I pass the raw JSON through without needing to add it to some parent node (such as body)?如何传递原始 JSON 而无需将其添加到某些父节点(例如正文)?
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.
我们可以创建一个 Model class 具有要存储在数据库中的属性。
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.然后可以创建 model 的 object 并将该 object 传递给
AddAsync()
方法。 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.当我们触发 post API 时,得到如下所示的响应。
As finally we can see the same record is stored in CosmosDB.最后我们可以看到相同的记录存储在 CosmosDB 中。
Just to formalize my comment as an answer: You're specifically creating the body
property of the Cosmos DB document you're creating:只是为了将我的评论形式化为一个答案:你专门创建了你正在创建的 Cosmos DB 文档的
body
属性:
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.同时,您忽略了传入的 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:由于您想保留该 ID,您可以复制该 ID(只要它在分区中保持唯一)而不是生成新的 GUID,并且还可以从
sourceJson
获取各个属性以避免嵌套的body
元素:
wait documentsOut.AddAsync(new
{
id = sourceJson.id,
storeName = sourceJson.storeName,
invoiceTotal = sourceJson.invoiceTotal
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.