I have a Cosmos DB stored procedure that creates a new document if it doesn't already exist and returns the existing or the new document. The procedure may be called from different processes. Can I be sure that the document is only created once even if several clients are trying to create it at the same time?
function createIfNotExists(param1, param2) {
var collection = getContext().getCollection();
// Query documents and take 1st item.
var query = 'SELECT * FROM c WHERE c.Param1="' + param1 + '" AND c.Param2="' + param2 + '"';
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
query,
function (err, items, options) {
if (err) throw err;
var response = getContext().getResponse();
if (!items || !items.length) {
var accepted = collection.createDocument(collection.getSelfLink(),
{
Param1: param1,
Param2: param2
},
function (err, itemCreated) {
if (err) throw err;
response.setBody(itemCreated);
});
if (!accepted) throw new Error('Could not create document');
}
else {
response.setBody(items[0]);
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}