Cosmos DB (1 / 62): Create a stored procedure that creates a document.
var createDocumentStoredProc = {
id: 'createMyDocument',
// This stored procedure creates a new item in the Azure Cosmos container
body: function createMyDocument(documentToCreate) {
// Code here
},
};
Answer:
var createDocumentStoredProc = {
id: 'createMyDocument',
// This stored procedure creates a new item in the Azure Cosmos container
body: function createMyDocument(documentToCreate) {
var context = getContext();
var collection = context.getCollection();
// Async 'createDocument' operation, depends on JavaScript callbacks
// returns true if creation was successful
var accepted = collection.createDocument(
collection.getSelfLink(),
documentToCreate,
// Callback function with error and created document parameters
function (err, documentCreated) {
// Handle or throw error inside the callback
if (err) throw new Error('Error' + err.message);
// Return the id of the newly created document
context.getResponse().setBody(documentCreated.id);
}
);
// If the document creation was not accepted, return
if (!accepted) return;
},
};