no records found in stored procedure cosmos db - azure-cosmosdb

I have written a simple cosmos stored procedure
function a()
{
var context = getContext();
var response = context.getResponse();
var collection = context.getCollection();
var collectionLink = collection.getSelfLink();
var filterQuery = 'SELECT * FROM c';
collection.queryDocuments(collectionLink, filterQuery, { pageSize: -1 },
function (err, documents) {
if (err) throw err;
if (!documents || !documents.length) {
var response = getContext().getResponse();
response.setBody('No Records found');
}
else {
response.setBody(response.getBody());
}
});
}
However on execution, I always get "No records found", though on running the query separately, I do get records. Also I have give partition key value.

Suppose you provide the incorrect partition key so that no data could be found.
SP codeļ¼š
function a()
{
var context = getContext();
var collection = context.getCollection();
var collectionLink = collection.getSelfLink();
var filterQuery = 'SELECT * FROM c';
collection.queryDocuments(collectionLink, filterQuery, { pageSize: -1 },
function (err, documents) {
if (err) throw err;
if (!documents || !documents.length) {
var response = getContext().getResponse();
response.setBody('No Records found');
}else {
var response = getContext().getResponse();
response.setBody(documents);
}
});
}
Sample data:
Provide partition key and execute:

Related

How to check if the emaiID exists or not in the dynamodb?

am using node js for the lambda function. I need to check whether the emailID exists or not in the dynamo db...If the emailID exists it should prompt to the user that emailid already exists if not it should store the values in the dynamo db ....
EmailID is the sort key
Customername is the primary key
How can i do that ..
Below is my code:
var doc = require('aws-sdk');
var dynamodb = new doc.DynamoDB()
var tableName = "Testing";
exports.handler = (event, context, callback) => {
var EmailID = event.EmailID; // or any other var which is having emaiID
console.log(event)
var params = {
TableName: "Testing",
Key: { EmailID : "abc#gmail.com",
CustomerName : "ABC"},
AttributeUpdates: {
verified: {
Action: "PUT",
Value: true
}
}
};
// Update the user.
dynamodb.update(params, function(err, data)
{
if (err)
{
console.log(JSON.stringify(err));
context.fail(JSON.stringify(err));
return;
}
context.succeed("User successfully updated.");
});
putItem
var AWS = require('aws-sdk');
var docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = (event, context, callback) => {
// TODO implement
var tableName = "Testing";
console.log(event.EmailID)
var parms = {
TableName : tableName,
Item : {
"EmailID" : event.EmailID,
"CustomerName" : event.CustomerName,
"PersonName" : event.PersonName,
"EmailSent" : event.EmailSent,
"Password" : event.Password
}
};
docClient.put(parms, function(err, data)
{
if (err){
callback(err)
}
else
{
callback(null,"Successfully updated data!!!")
}
})
};
To achieve this I would use the Put operation and use the "exists" parameter. Setting it to false will make sure the put operation will fail if an item already exists. When there is no match then put will insert the record.
For more details on how to use this operation in javascript please check out the documentation:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#putItem-property
So in your put example you could add the following to your params:
var AWS = require('aws-sdk');
var docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = (event, context, callback) => {
// TODO implement
var tableName = "Testing";
console.log(event.EmailID)
var parms = {
TableName: tableName,
Item: {
"EmailID": event.EmailID,
"CustomerName": event.CustomerName,
"PersonName": event.PersonName,
"EmailSent": event.EmailSent,
"Password": event.Password
},
ConditionExpression: "attribute_not_exists(EmailID)"
};
docClient.put(parms, function (err, data) {
if (err) {
callback(err)
}
else {
callback(null, "Successfully updated data!!!")
}
})
};

How to pass variable key value in dynamodb

Am trying to get the items from DynamoDB table based on the current date. Using the date value in string format when am trying to run the below piece of code, its error out saying:
{
"errorMessage": "ERROR: Dynamo failed: TypeError: Cannot read property 'datatype' of undefined"
}
Below is the piece of code:
exports.handler = function(event, context) {
console.log("Request received:\n", JSON.stringify(event));
console.log("Context received:\n", JSON.stringify(context));
var doc = require('dynamodb-doc');
var dynamodb = new doc.DynamoDB();
var params = {
Key: {
"abc" : datetime1
},
TableName: 'myTable',
ProjectionExpression: 'message'
};
var Message = callback();
var datetiem = new Date().toISOString().split('T')[0];
console.log('date is ', datetiem); // prints 2018-01-09
var datetime1 = JSON.stringify(datetiem);
console.log(datetime1); //prints "2018-01-09"
function callback (message) {
dynamodb.getItem(params, function (err, data) {
if (err) {
context.fail('ERROR: Dynamo failed: ' + err);
} else {
console.log('Dynamo Success: ' + JSON.stringify(data, null, ' '));
console.log('data', data)
let Message = data['Item'].message;
console.log('test',Message);
}
});
}
};
It runs fine if I pass the value directly i.e. "abc" : "2018-01-09"
Can someone please advice?
I'm not sure your datetime1 variable is defined when you use it in parameters. Try this:
exports.handler = function(event, context) {
console.log("Request received:\n", JSON.stringify(event));
console.log("Context received:\n", JSON.stringify(context));
var doc = require('dynamodb-doc');
var dynamodb = new doc.DynamoDB();
var Message = callback();
var datetiem = new Date().toISOString().split('T')[0];
console.log('date is ', datetiem); // prints 2018-01-09
var datetime1 = JSON.stringify(datetiem);
console.log(datetime1); //prints "2018-01-09"
var params = {
Key: {
"abc" : datetime1
},
TableName: 'myTable',
ProjectionExpression: 'message'
};
function callback (message) {
dynamodb.getItem(params, function (err, data) {
if (err) {
context.fail('ERROR: Dynamo failed: ' + err);
} else {
console.log('Dynamo Success: ' + JSON.stringify(data, null, ' '));
console.log('data', data)
let Message = data['Item'].message;
console.log('test',Message);
}
});
}
};

Cordova SQLite class - cannot return value from database

So, I'm building an app with Cordova and SQLite and below is the object Storage I created to handle the database properties and methods.
function Storage(connection, platform)
{
if (platform == 'mobile') {
this.db = window.sqlitePlugin.openDatabase({name: connection.name, location: connection.location});
} else if (platform == 'web') {
this.db = window.openDatabase(connection.name, connection.version, connection.mode, -1);
}
this.read = function(sql, vals) {
var rows = null;
this.db.transaction(function(tx) {
tx.executeSql(sql, vals, function(tx, res) {
rows = res.rows;
});
}, function(error) {
console.log('Transaction error: '+error.message);
});
return rows;
};
};
var connection = {
name: 'database.db',
version: '1.0',
mode: 'Development'
};
var db = new Storage(connection, 'web');
var sql = '';
sql += 'SELECT *';
sql += ' FROM countdown';
sql += ' WHERE countdown_status != ?;';
var rows = db.read(sql, [1]);
console.log(rows);
This code logs 'null' and I don't know why since I have data into my database. And when I try to log from within the tx.executeSql method, it logs the data from database.
Any ideas on why I cannot get this data out of that function?
Thanks a lot.
the db read is asynchronous - it needs to return the data to a callback function like so:
getHighScore: function (type,callback) {
var query = "SELECT Value FROM HighScore where Type = '" + type + "';";
playedDb.transaction(function (tx) {
tx.executeSql(query, [], function (tx, res) {
var out;
if (typeof res.rows.item(0) === "undefined") {
if (typeof callback === "function") {
callback(-1);
return;
};
} else {
out = res.rows.item(0).Value
//task 301 only allow alphanumeric and decimal point (for version)
out = String(out).replace(/[^0-9a-z\.]/gi, '');
if (typeof callback === "function") {
callback(out);
return;
};
}
}, function (e) {
console.log("getHighScore FAILED: " + e.message);
if (typeof callback === "function") {
callback(-2);
return;
};
});

How to update a document in Documentdb using queries?

How to update a document in Document db using queries ( basically want to update a document using a stored procedure)?
The following sample might be what you need: https://github.com/aliuy/documentdb-serverside-js/blob/master/stored-procedures/update.js.
Here's a simplified version:
function updateSproc(id, update) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();
var response = getContext().getResponse();
tryQueryAndUpdate();
function tryQueryAndUpdate(continuation) {
var query = {query: "select * from root r where r.id = #id", parameters: [{name: "#id", value: id}]};
var requestOptions = {continuation: continuation};
var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, documents, responseOptions) {
if (err) throw err;
if (documents.length > 0) {
tryUpdate(documents[0]);
} else {
throw new Error("Document not found.");
}
});
}
function tryUpdate(document) {
var requestOptions = {etag: document._etag};
var fields, i;
fields = Object.keys(update);
for (i = 0; i < fields.length; i++) {
document[fields[i]] = update[fields[i]];
}
var isAccepted = collection.replaceDocument(document._self, document, requestOptions, function (err, updatedDocument, responseOptions) {
if (err) throw err;
response.setBody(updatedDocument);
});
}

Meteor app stuck at 100% CPU when client loads - how to fix?

My meteor app has been hitting 100% cpu on the server when I load certain pages of the app on the client. It causes the app to hang for other clients. How can I fix it?
I suspect that I can improve performance by publishing or subscribing more efficiently for those particular pages. I am not sure, however, if doing more calculations in the publish functions to reduce the fields being sent to the client helps or hurts. While the data size being sent decreases, the number of calculations before sending the data increases. Should I optimize for more calculations and less data or less calculations and more data? Specifically, what criteria do I use to decide?
My publish function:
Meteor.publish('userdata', function(id) {
if (!this.userId) return [];
var user = Meteor.users.findOne(this.userId);
if (!user) return [];
if (isStaff(this.userId)) user = Meteor.users.findOne(id);
var tasks;
var emails = [];
var network = user.users ? [user.users] : [];
var meals;
if (isStaff(this.userId) && this.userId === id) { //staff looking at own profile
tasks = Tasks.find({users: this.userId, status: "active"}, {sort: { taskName: 1 } });
emails = Emails.find({staffId: id});
meals = Meals.find({userId: this.userId});
}
else { //staff looking at other profiles
meals = Meals.find({userId: id});
var completedTasks = [];
if (user.userTaskStatus) {
completedTasks = user.userTaskStatus.map(function (thisTaskStatus) {
if (thisTaskStatus.status !== "incomplete") return thisTaskStatus.taskId;
});
}
var allUserTasks = Tasks.find({users: user._id});
var showTaskIds = [];
allUserTasks.forEach(function (thisTask) {
if (!thisTask.prereqs) showTaskIds.push(thisTask._id);
else {
var prereqs = thisTask.prereqs;
var pushTaskFlag = true;
for(var i=0; i<prereqs.length; i++)
if (completedTasks.indexOf(prereqs[i]) < 0) {
pushTaskFlag = false;
break;
}
if (pushTaskFlag) showTaskIds.push(thisTask._id);
}
});
tasks = Tasks.find({_id: {$in: showTaskIds}, visible: true, status: "active"}, {sort: { taskName: 1 } });
var network = user.users ? user.users.push(id) : [id];
if (isStaff(this.userId)) emails = Emails.find({userId: {$in: network}}, {sort: {date: -1}});
}
network.push(user._id);
var calls = Calls.find({$or: [{to:user.phone},{from:user.phone}] });
var callStaffIds = calls.map(function (thisCall) {
return thisCall.staff;
});
var callNoteIds = calls.map(function (thisCall) {
return thisCall.noteId;
});
var notes = Notes.find({
$or:[
{userId: this.userId},
{noteId: {$in: callNoteIds}}
]
});
var noteStaffIds = notes.map(function (thisNote) {
return thisNote.staff;
});
var allUserIds = network.concat(callStaffIds, noteStaffIds);
var groups = [];
if (user.groups) groups = user.groups;
return [
Meteor.users.find({_id: {$in: allUserIds}}, {fields: {services: 0}}),
tasks,
Groups.find({_id: {$in: groups}}, {sort: { groupName: 1 } }),
emails,
calls,
notes,
meals
];
});

Resources