James Monger
James Monger

Reputation: 10675

Check if CosmosDB item exists without try/catch

I am using the Node.js CosmosDB library and I want to check if an item exists.

I have seen some examples which recommend the following:

const i = container.item(id);

try {
    const { item } = await i.read();
    // item exists
} catch(e) {
    // item does not exist
}

But I don't want to use exceptions for flow control. I also want to avoid using container.items.query - I want to use container.item if possible.

Can I do this?


The reason I would like to know how to do this, is I need to call Item.replace to update an item, so I would like to do this:

const i = container.item(id);

if (i.exists() === false) {
    return;
}

i.replace(replacement);

However, if I have to use container.items.query, I will have to do this:

const result = container.items.query(myQuery);

if (result.current() === undefined) {
    return;
}

container.item(id).replace(replacement);

Upvotes: 4

Views: 5550

Answers (1)

Chris Anderson
Chris Anderson

Reputation: 8515

Right now, 404 means we throw.

We're thinking about making not throw. I just created an item on GitHub to track that. https://github.com/Azure/azure-cosmos-js/issues/203

Depending on the size of your document, query can actually be cheaper, because you can query for just the id or _etag instead of the full document. For small documents, read will be cheaper, though.

As a workaround, does upsert work for you?

-- EDIT 1 --

Another, kinda hacky option is to handle the error yourself since it's all promises.

const handle404 = (err) => {
    if(err.code && err.code === 404) {
        return { body: undefined, headers: err.headers };
    } else {
        throw err;
    }
} 

const { body: item } = await container.item(id).read().catch(handle404);

Upvotes: 1

Related Questions