I have a pre trigger for create new item in cosmo db collection. The trigger will read a meta file and then update the item to be created. the partition key is /id and the _sequence document is just a meta document keeps track of how many items we have in the collection. However, the trigger always raise error "Fail to find the metadata document" even though it exists in the collection. Can anyone tell me what I have done wrong?
function updateRefnumber() {
var context = getContext();
var collection = context.getCollection();
var collectionLink = collection.getSelfLink();
var request = context.getRequest();
var itemToCreate = request.getBody();
getAndUpdateSequence();
function getAndUpdateSequence() {
// Get the meta document. We keep it in the same collection. it's the only doc that has .isMetadata = true.
var isAccepted = collection.queryDocuments(collectionLink, "SELECT * FROM root r WHERE r.id = '_sequence'", function (err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) throw new Error('Failed to find the metadata document.');
// The metadata document.
var metaDoc = feed[0];
if (metaDoc.createdDocuments == undefined) {
throw new Error('createdDocuments does not exit on object.');
}
var sequence = metaDoc.createdDocuments += 1;
itemToCreate.refNumber = 'PBC-' + sequence;
// Update/replace the metadata document in the store.
var isAccepted = collection.replaceDocument(metaDoc._self, metaDoc, function (err) {
if (err) throw err;
});
if (!isAccepted)
throw new Error('The call replaceDocument(metaDoc) returned false.')
else
request.setBody(itemToCreate);
});
if (!isAccepted) throw new Error('The call queryDocuments for metaDoc returned false.');
return;
}
}