Skip to content

Instantly share code, notes, and snippets.

@davidobrien1985
Last active December 22, 2023 10:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidobrien1985/79fa2d322f082563f566d97e8c7978a3 to your computer and use it in GitHub Desktop.
Save davidobrien1985/79fa2d322f082563f566d97e8c7978a3 to your computer and use it in GitHub Desktop.
Cosmos DB Stored Procedure to update all documents based on query with a new property called inventoryStatus. Change lines 27 and 37 to create a different property.
function addProperty(continuationToken) {
var response = getContext().getResponse();
var collection = getContext().getCollection();
var updated = 0;
if (continuationToken) { // Parse the token
var token = JSON.parse(continuationToken);
if (!token.queryContinuationToken) {
throw new Error('Bad token format: no continuation');
}
updated = token.updatedSoFar;
query(token.queryContinuationToken);
}
else {
query();
}
// Function within the main stored procedure function
function query(continuation) {
var requestOptions = { continuation: continuation };
// Query all documents in one logic partition
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root r WHERE not is_Defined(r.inventoryStatus)',
requestOptions,
function (err, feed, responseOptions) {
if (err) throw err;
if (!feed || !feed.length) {
response.setBody('no docs found');
}
else {
feed.forEach(element => {
element.inventoryStatus = "active";
collection.replaceDocument(element._self, element, function (err) {
if (err) throw err;
})
updated++
})
}
if (responseOptions.continuation) {
// Continue the query
query(responseOptions.continuation)
} else {
// Return the count in the response
response.setBody({ count: updated, continuation: null });
}
});
if (!isAccepted) {
var sprocToken = JSON.stringify({
updatedSoFar: updated,
queryContinuationToken: continuation
});
response.setBody({ count: null, continuation: sprocToken });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment