Cosmos CRUD
February 02, 2020
Cosmos DB JavaScript SDK is clean - I like it. But I feel like I always end up forgetting how to CRUD.
For the uninitiated in database street-slang, CRUD means Create, Read, Update And Delete. Feel free to use that if you find yourself in a turf war or dance-off.
Well, I take that back. I can “read” everything purty gud. Actually, I can “create” as well. It’s the retrieving of one item that always throw me off. This is because of partition keys. Partition keys always hang me up (because I am but a simple man) and, well, I need a reminder for how they do and don’t affect retrieving an item, so that’s what I’m going to document in this here article.
Assume that we’re working with the following document structure with a partition key on “/brand/name”.
Assume that all of the following examples have the following connection information…
Creating an item
Note that Cosmos DB auto-creates an id if you don’t pass one in. It will be a GUID.
Reading all items
Reading one item
Sometimes you don’t have a partition key. In that case, you’ll want to pass undefined
as the second parameter.
Update an item
Note that you have to include the id on the object that you pass in to the
replace
function. Even though you already specified it when you retrieved the item to update.
Delete an item
Partition key values vs names
The main takeaway from this article (besides my poor use of grammer and analogy) should be that CosmosDB wants a partition key VALUE, not name. When I was first working with the SDK, I would try to pass in the partition key name (/brand/name). This would throw an error telling me that an object with id of whatever didn’t exist. That’s because I needed to pass in the value of the partition key, not the name. This is why you need to pass in undefined if you do not have a partition key defined for your collection.
There is a pretty good tutorial you can go through here that covers this in more detail and shows it in a Node/Express context.
I hope this helps. Good luck out there.