Last active
December 22, 2023 10:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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