DocumentDB: Delete a document by ID - azure

I'm using a new database from Microsoft called DocumentDB. Now I want to delete a document by ID, but I cannot figure out, how to do this. Delete operation in DocumentDB requires self-links and they are different from my own ids.
using (var client = new DocumentClient(EndPoint, AuthKey))
{
await client.DeleteDocumentAsync("**self-link here**");
}
I can execute an additional query to find the self-link and then pass it, but this will require two operations instead one and that is what I'd like to avoid. Is there a better way to remove an entry by ID without using queries or stored procedures?

* UPDATE * This feature has now been implemented
* ORIGINAL ANSWER *
Not today, no. You can head to http://feedback.azure.com/forums/263030-documentdb and vote for the feature there.

Here is how I am deleting document
{
var docUri = UriFactory.CreateDocumentUri(_documentDataBaseId, _documentCollectionId, docId);
await _documentClient.DeleteDocumentAsync(docUri);
}

This features has now been implement (as of the 8/2015 - https://feedback.azure.com/forums/263030-documentdb/suggestions/6333050-it-should-be-possible-to-remove-a-document-by-id

as there's no solution for this case I'd recommend to retrieve all the documents in the existing collection to get access to the SelfLink and _rid values.
I just started a mini wrapper to get access to DocumentDB in Universal Apps and hopefully CrossPlatform using Xamarin: https://github.com/JorgeCupi/documentDB-Win10UAP-wrapper feel free to give me any feedback, participate or request some needed methods.

I have tried this code in nodejs to deletebyId and it works for me.
deleteDocumentById: function(params, callback) {
var self = this,
query= params.query,
collection = params.collection;
client.queryDocuments(collection._self, query, function(err, docs) {
if (err) {
return callback(err);
}
client.deleteDocument(docs[0]._self, docs[0], function(err, success) {
if (err) {
return callback(err);
}
callback(null, success);
});
});
}

I was continuously receiving this error: Microsoft.Azure.Documents.DocumentClientException:
Entity with the specified id does not exist in the system.,
The main trick of deleting is PartionKey id. You suppose inside PartionKey provide id
like in the code example.
I have tried many ways, but I was always receiving different errors...Only this solution worked for me.
await client.DeleteDocumentAsync(input[0].SelfLink,
new RequestOptions
{
PartitionKey = new PartitionKey(input[0].Id)
});
Hope this helps :)

Related

How do I retrieve anything from cloud datastore in node?

I'm trying to access data that I have stored in datastore (in datastore mode). For some reason, I can't access any data it seems.
Things I've tried.
Access using a key
const datastore = new Datastore({projectId: '...'});
const key = datastore.key([<kind>, <id>]);
return datastore.get(key, (err, entity, x) => {
console.log("yolo", err, entity, x);
return entity;
});
Using a query
const query =
datastore.createQuery(<kind>);
return datastore.runQuery(query, (err, e, nq) => {
console.log(err, e, nq);
return e;
});
Both of the above yields no result. I am 100% sure I have typed the kind correctly.
So this was a stupid mistake on my end, but I keep the question in case someone else does the same mistake.
What I did when I created the entry in datastore was that I put it in a namespace, but then I didn't provide the namespace when I queried for it. Just providing the namespace and I was all good.

How to set push key when pushing to firebase database?

When I write data to firebase database from both frontend(Angular 4) and backend(firebase functions), there is a push key generated by firebase. With this key, I cannot access data in the future because the key is unique. I am wondering is any way I can set the key myself or I can access the data without knowing the key?
Here is my code from frontend:
this.db.list(`${this.basePath}/`).push(upload);
Here is my code from backend:
admin.database().ref('/messages').push({original: original}).then(function (snapshot) {
res.redirect(303, snapshot.ref);});
All data I pushed will be under path/pushID/data
I cannot access data without knowing the pushID.
The best case I want is path/my own pushID/data
Thanks so much for help!!
If you want to loop through all messages:
var ref = firebase.database().ref("messages");
ref.once("value", function(snapshot) {
snapshot.forEach(function(message) {
console.log(message.key+": "+message.val().original);
});
});
If you want to find specific messages, use a query:
var ref = firebase.database().ref("messages");
var query = ref.orderByChild("original").equalTo("aaaa");
query.once("value", function(snapshot) {
snapshot.forEach(function(message) {
console.log(message.key+": "+message.val().original);
});
});
For much more on this, read the Firebase documentation on reading lists of data, sorting and filtering data, and take the Firebase codelab.
The keys should be unique in any way. You can set your own key like this instead of push
admin.database().ref('/messages/'+ yourUniqueId).set({original: original}).then(function (snapshot) {
res.redirect(303, snapshot.ref);});
yourUniqueId can be auth uid or email of user, like something unique.

newbie node.js bot integration with database lookup (looking for best practice)

OK, new to Node.js and botframework. I built first bot using Azure site and downloaded the code. Chose the Luis integrated bot template.
I understand (finally) the event driven model of node.js and the concept of callbacks.
I have the code snippet below. When Luis finds an intent of "Help" it triggers this function. In turn, I have database calls to lookup the entity. Within the database I have an entity, response (if entity is bottle, answer "Recycle").
I have that code working too.
Below the first block is a function handleHelpRequester which is the callback function, I have that working as well. Where I am a little stuck (best practice) is that in this callback function I want to send something to the session object (session.send toward the bottom of the function).
Since I don't create the session object (directly) I'm not sure on the options.
Should I pass the session object to the database function, then pass it back?
Should I create a global variable and set it to the session object (I'm concerned that if multiple people are using this bot then this approach won't work).
I'm open for suggestions.
Thanks
.matches('Help', (session, args) => {
var entities = args.entities;
var itype = builder.EntityRecognizer.findEntity(args.entities, 'ItemTypes');
var respondToUser = '';
var msg = 'Initialized';
// if there is an entity provided, perform a lookup of the entity.
if (itype.entity !== null) {
//Use session.sendTyping so the user thinks something is happening rather than being ignored while we do the lookup in SharePoint.
session.sendTyping();
//perform lookup
respondToUser = sp.lookupEntity(itype.entity, handleHelpRequest);
};
})
function handleHelpRequest(err, respondToUser) {
var msg = 'uninitialized';
if (err = 'success') {
console.log('Respond to user from matches:'.concat(respondToUser));
//return from lookup
if (respondToUser === 'No match found') {
msg = 'I think you are asking for help, but I don\'t understand what you need help with.';
}
else {
msg = 'I can help you with that, \'%s\'.', respondToUser;
}
console.log(msg);
session.send(msg);
//The following two lines are for debugging
session.send('How may I assist you? ' + JSON.stringify(args));
session.send('Value of entity you said: \'%s\'.', itype.entity);
}
else {
console.log('an error occurred');
}
}
If you want to have access to the session object, then pass it as a parameter to your helper function.
Example:
function handleHelpRequest(session, err, respondToUser) {
// do session stuff
}

How to delete on based of subkey using hset in redis in node js app

I am trying to use redis in my nodejs application. I am able to save and retrieve value perfectly. I am using hash which allows me to have single unique key as well sub-keys. Here offer id is my sub key and offer is key.
I am saving offer like below
let offer = {
offerId: req.query.id,
offerName: req.query.offerName,
offerVendor: req.query.offerVendor
}
client.hset('offer', offer.offerId, JSON.stringify(offer), redis.print);
and retrieving value like below
try {
console.log('ping response:', await client.ping());
const offerId = req.query.id;
client.hget('offer', offerId, function(err, reply){
let offer = JSON.parse(reply);
res.send(offer);
});
} catch(err) {
console.log('ping error:', err);
}
I want to delete offer based on id as like saving or getting on based of id. I have gone through documentation https://github.com/NodeRedis/node_redis#usage-example but didn't find there.
What is the way to do delete offer based on id ?
If you already have the offer id, you can delete it from the offer hash using the hdel command. Your code would look something like:
client.hdel('offer', id)
The result from the call will be an integer count of the number of keys deleted. If you don't know the client id, you can look for it using the hscan command.

Overriding delete operation on Azure Mobile Services table

I'd like to override delete operation on my Azure Mobile Services table to make it more like update then real delete. I have additional column named IsDeleted and I'd like to set it's value to true when delete operation is executed.
I figured out, that what I need is:
fire my own 'update' inside del function,
delete current request.execute()
prepare and sent response by myself
That meens my del function should look like that:
function del(id, user, request) {
// execute update query to set 'isDeleted' - true
// return standard response
request.respond();
}
As you can see I'm missing the first part of the function - the update one. Could you help me writing it? I read Mobile Services server script reference but there is no info about making additional queries inside a server script function.
There are basically two ways to do that - using the tables object, and using the mssql object. The links point to the appropriate reference.
Using mssql (I didn't try it, you may need to update your SQL statement):
function del(id, user, request) {
var sql = 'UPDATE <yourTableName> SET isDeleted = true WHERE id = ?';
mssql.query(sql, [id], {
success: function() {
request.respond(statusCodes.OK);
}
});
}
Using tables (again, only tested in notepad):
function del(id, user, request) {
var table = tables.getTable('YourTableName');
table.where({ id: id }).read({
success: function(items) {
if (items.length === 0) {
request.respond(statusCodes.NOT_FOUND);
} else {
var item = items[0];
item.isDeleted = true;
table.update(item, {
success: function() {
request.respond(statusCodes.OK, item);
}
});
}
}
});
}
There is a Node.js driver for SQL Server that you might want to check out.
The script component of Mobile Services uses node.js. You might want to check out the session from AzureConf called Javascript, meet cloud

Resources