I am modifying a Json document through code. The Json has array nested items. My code is failing because I believe its not able to handle Json documents where that particular array is empty. How can I check for null or empty arrays and make this code work for only arrays that have data.
store.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName",
new IndexQuery { Query = "Tag:patrons" },
new[]
{
new PatchRequest
{
Type = PatchCommandType.Modify,
Name = "Privilege",
Nested = new[]
{
new PatchRequest {Type = PatchCommandType.Set, Name="Level",
Value="Gold"},
}
}
}, allowStale: false);
Json document looks like:
{
"Privilege": [{
"Level": "Gold",
"Code": "12312",
"EndDate": "12/12/2012"
}],
"Phones": [{
"Cell": "123123",
"Home": "9783041284",
"Office": "1234123412"
}]
"MiddleInitial":"F"
}
Some Json docs can look like (notice Privilege is an empty array in this case)
{
"Privilege": [],
"Phones": [{
"Cell": "123123",
"Home": "9783041284",
"Office": "1234123412"
}]
"MiddleInitial":"F"
}
The patching command expects the data to be there, so you need to use an index to find the docs that don’t have an empty
Privilegeslist.First you need an index like this:
Then you only apply the patch to the docs where
HasPrivileges = true, like so:I’ve created a full code sample, any problems let me know.