Tristan Rhodes
Tristan Rhodes

Reputation: 393

DocumentDB Replace not Working

I recently realized that DocumentDB supports stand alone update operations via ReplaceDocumentAsync.

I've replaced the Upsert operation below with the Replace operation.

var result = _client
    .UpsertDocumentAsync(_collectionUri, docObject)
    .Result;

So this is now:

var result = _client
    .ReplaceDocumentAsnyc(_collectionUri, docObject)
    .Result;

However, now I get the exception:

Microsoft.Azure.Documents.BadRequestException : ResourceType Document is unexpected. ActivityId: b1b2fd71-3029-4d0d-bd5d-87d8d0a2fc95

No idea why, upsert and replace are of the same vein and the object is the same that worked for upsert, so I would expect it to work without problems.

All help appreciated.

Thanks

Update: Have tried to implement this using the SelfLink approach, and it works for Replace, but selflink does not work with Upsert. The behavior is quite confusing. I don't like that I have to build a self link in code using string concatenation.

Upvotes: 6

Views: 3812

Answers (3)

Jorn.Beyers
Jorn.Beyers

Reputation: 2054

In order to update a document, you need to provide the Collection Uri. If you provide the Document Uri it returns the following:

ResourceType Document is unexpected.

Maybe the _collectionUri is a Document Uri, the assignment should look like this:

_collectionUri = UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName);

Upvotes: 2

Yannick Meeus
Yannick Meeus

Reputation: 5910

You can build a document link for a replace using the UriFactory helper class:

var result = _client
    .ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, docObject.Id), docObject)
    .Result;

Unfortunately it's not very intuitive, as Larry has already pointed out, but a replace expects a document to already be there, while an upsert is what it says on the tin. Two different use-cases, I would say.

Upvotes: 3

Larry Maccherone
Larry Maccherone

Reputation: 9533

I'm afraid that building the selflink with string concatenation is your only option here because ReplaceDocument(...) requires a link to the document. You show a link to the collection in your example. It won't suck the id out and find the document as you might wish.

The NPM module, documentdb-utils, has library functions for building these links but it's just using string concatenation. I have seen an equivalent library for .NET but I can't remember where. Maybe it was in an Azure example or even in the SDK now.

Upvotes: 3

Related Questions