Reputation: 60811
I'm attempting to run some patch operations:
ItemResponse<dynamic> response = await _container.PatchItemAsync<dynamic>(
id: loanParent.LoanNumber,
partitionKey: new PartitionKey(loanParent.LoanNumber),
patchOperations: new[] {
PatchOperation.Replace("/loandetails/loanname", loanParent.Loan.LoanDetails.LoanName),
PatchOperation.Replace("/loandetails/loandescription", loanParent.Loan.LoanDetails.LoanDescription)
}
);
However, I'm getting this exception because those nodes do not exist yet. Here's the full document:
{
"loannumber": "abc123",
"id": "abc123",
"participants": [
{
"firstname": "alex",
"lastname": "gordon"
},
{
"firstname": "liza",
"lastname": "gordon"
}
],
"_rid": "1sAyAggggggA==",
"_self": "dbs/1sAyAA=gggggAAAAAAAA==/",
"_etag": "\"d900c069-0000-4440-0000-63642d840000\"",
"_attachments": "attachments/",
"_ts": 1ddd636
}
Microsoft.Azure.Cosmos.CosmosException : Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: a6ab67d6-f73e-4b3c-b03e-1d9b6cc54dba; Reason: (Message: {"Errors":["For Operation(1): Given Operation can only create a child object of an existing node(array or object) and cannot create path recursively, no path found beyond: 'loandetails'. Learn more: https://aka.ms/cosmosdbpatchdocs"]}
How do we create the node structure if it does not exist?
Upvotes: 2
Views: 694
Reputation: 849
For anyone else coming here after realising that PatchOperation.Replace
throws an error if field doesn't exist and wanting to add or replace a field instead (aka do an upsert).
The good new is that their upsert equivalent is an Add
operation (aka PatchOperation.Add
) which will properly add or replace field value like any good little upsert should do.
Here is some git discussion mentioning it, unlike their rather unhelpful documentation: https://github.com/AzureCosmosDB/PatchPrivatePreviewFeedbackGroup/issues/2
Upvotes: 0
Reputation: 222682
Patch works on an existing document, you need to make sure the object exists before you perform any operations such as add,remove,replace,set and increment.
In this case first you can use Add operator to create the loandetails
and then the subsequent operations can be performed
Upvotes: 1