delete node in firebase - javascript

been reading docs and other posts but I am unable to remove a node. I am attempting to select the node by a value.
var eventContactsRef = firebase.database().ref('events-contacts');
eventContactsRef.orderByChild('eventContactId').equalTo(eventContactId);
then call the remove method on the result
eventContactsRef.remove(function (error) {
console.log(error);
});
nothing happens except a null error value. I am using the latest firebase, most examples are for older versions so I am unsure if I need to get the key and then attempt to delete with that as a reference?
This is the first time using firebase so I am not sure if I have saved the data correctly. here is code to save.
var key = firebase.database().ref().child('event-contacts').push().key;
var url = firebase.database().ref('/event-contacts/' + key);
url.set(eventContacts);
and screenshot

You cannot remove a query itself. You can only remove the results that match a query.
var eventContactsRef = firebase.database().ref('events-contacts');
var query = eventContactsRef.orderByChild('eventContactId').equalTo(eventContactId);
query.on('child_added', function(snapshot) {
snapshot.ref.remove();
})

Related

Firebase query undefined when using react-firebase-hooks

I was following Fireship's building chat app video (this part is around 3:30-4 minutes) but I am trying do something different, just using it for oauth and database setup help. I made a simple database on it, then tried to follow the query format where the collection grab and query seem to work fine since I can console.log them. But when I try to use the collection data, it is undefined. I also found another post on here similar that queried it differently and tried to use an grab a specific variable, but doing that just left me with an error saying "query2 is not a function". So below I added 2 versions of what I tested. ListItem is the collection name, and checked is one of my variables in the document.
function GrabData(){
const dataRef = firestore.collection('ListItem')
console.log(dataRef)
const query = dataRef.orderBy('createdAt')
console.log(query)
const [items1] = useCollectionData(firestore.collection("ListItem"))
console.log(items1)
const [items2] = useCollectionData(query, {idField: 'checked'})
console.log("items = " + items2)
UPADTE: From the error message it seems I needed to add permissions. However, instead of undefined it simply returns empty arrays. And I querying it incorrectly or missing something?
function GrabData(){
const dataRef = firestore.collection('ListItem')
console.log(dataRef)
const query = dataRef.orderBy('createdAt')
console.log(query)
const [items] = useCollectionData(query, {idField: 'checked'})
console.log(items)
const [values, loading, error, snapshot] = useCollectionData(query, {idField: 'checked'});
console.log(values)
console.log(snapshot)
UPDATE 2: I changed the if false to if true in the firebase edit rules tab
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
To fix the problem I had, edit the firestore permissions from "allow read, write: if false;" change the false to true. Also, make sure that you don't define a variable with the name query since you need to import the query function from firebase/firestore. Otherwise it will be overwritten and throw an error

i want to retrieve firebase database data with the child value

query.once("value") .then(function(snapshot) {
var childData = snapshot.val().user_name;
var childData2 = snapshot.val().user_id;
document.writeln(childData);
document.writeln("\n");
document.writeln(childData2);
});
this is the code i used for retrieving firebase database value using parent value
what changes should i make in this code for retrieving the parent values using the child value
I would like to retrieve user_name with help of password.
And also i want it to be work for other records in the users.
If the password is "2110" you can retrieve the user with:
var passwordToLookFor = "2110";
var ref = firebase.database().ref("users");
var query = ref.orderByChild("password").equalTo(passwordToLookFor);
query.once(function(snapshot) {
snapshot.forEach(function(child) { // loop over the results
console.log(child.key);
console.log(child.val().user_name);
});
});
As Doug commented, please take a moment to read the Firebase documentation on ordering and querying, as it will save you many questions going forward.

Stored procedure azure Cosmos DB returns empty collection

I tried to create a stored procedure using the sample sp creation code from Azure docs, but i couldn't fetch the collection details. It always returns null.
Stored Procedure
// SAMPLE STORED PROCEDURE
function sample(prefix) {
var collection = getContext().getCollection();
console.log(JSON.stringify(collection));
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root r',
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var response = getContext().getResponse();
var body = { prefix: prefix, feed: feed[0] };
response.setBody(JSON.stringify(body));
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
The console shows only this.
the results shows no doc found because of not getting collection.I have passed the partition key at time of execution via explorer.
I had a similar issue. I think the Azure portal doesn't execute stored procedures properly when the partition key is not a string.
In my case I had a partitionKey that is a number. When I executed the stored procedure via the portal I always got an empty resultSet, even though I had documents in my database. When I changed the structure a little, and made my partitionKey a string, the stored procedure worked fine.
Did you create the ToDoList Database with the Items Collection? Yo can do this from the Quick start blade in the Azure portal.
And then create an SP to run against that collection. There is no partition key required, so no additional params are required (leave blank).
The Collection is created without any documents. You may choose to add documents via the Query Explorer blade or via the sample ToDoList App that is available via the Quick start blade.
You are debugging in a wrong way.
It is perfectly fine to see "{\"spatial\":{}}" in your console log, even if the collection has items. Why? well because that is a property of that object.
So regarding what you said:
the results shows no doc found because of not getting collection
is false. I have the same console log text, but I have items in my collection.
I have 2 scenarios for why your stored procedure return no items:
I had the same issue trying on azure portal UI(in browser) and for my surprise I had to insert an item without the KEY in order that my stored procedure to see it.
On code you specify the partition as a string ie. new PartitionKey("/UserId") instead of your object ie. new PartitionKey(stock.UserId)

Update another collection in an Azure Document DB stored procedure

We need to update the all the documents in a collection to change their shape. We'd like to record an audit of the change in a different collection where we will store a document which contains the old and new version. In order to make this change atomic, we are using a stored proc.
The issue we are facing is updating another collection from a stored proc. It seems the audit document is always written into the collection the stored proc belongs to.
I have written up a sample stored proc:
function sample(prefix) {
var context = getContext();
var fooCollection = context.getCollection();
var barCollection = context.getCollection("BarCollection");
// Query documents and take 1st item.
var isAccepted = fooCollection.queryDocuments(
fooCollection.getSelfLink(),
'SELECT * FROM root r',
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!feed || !feed.length) context.getResponse().setBody('no docs found');
else {
var fooDoc = feed[0];
var barDoc = {
"foo" : fooDoc,
"bar" : "bar"
}
var isAccepted2 = barCollection.createDocument(barCollection.getSelfLink(), barDoc);
if (!isAccepted2) throw new Error('The query was not accepted by the server.');
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
In this sample, my stored proc is saved in the FooCollection. I get a document and try to save a copy into the BarCollection. The new document is always saved into the FooCollection.
Is this scenario supported in Document DB? If so, what changes do I need to make the stored proc to make it work?
DocumentDB stored procedures are collection-scoped. You will not be able to write audit info to a separate collection; you'd need to write to the same collection.

Unable to update each column of Parse Object

I am updating an object. I first find it by doing the following:
**EDIT**
Additional code added for setting and saving the object.
var query = new Parse.Query(iBeacon);
query.equalTo("uuid", searchUUID.children("input[type=text]").val().toString());
query.find({
success: function(results) {
var detailsObject = results[0];
//tduuid, tdoffer, tdproximity etc are globals intitialized earlier in code
//from values obtained from html table cells
var uuid = tduuid.children("input[type=text]").val().toString();
var offer = tdoffer.children("input[type=text]").val().toString();
var prox = parseInt(tdproximity.children("input[type=text]").val().toString());
var campaignId =tdcampaignId.children("input[type=text]").val().toString();
var location = tdGeoLocation.children("input[type=text]").val().toString();
var subLoc = tdinStoreLocation.children("input[type=text]").val().toString();
detailsObject.set("proximity", prox);
detailsObject.set("campaignId", campaignId);
detailsObject.set("location", location);
detailsObject.set("sub_location", subLoc);
detailsObject.set("uuid", uuid);
detailsObject.save(null, {
success: function(detailsObject) {
var content = Parse.Object.extend("Content");
var contentQuery = new Parse.Query(content);
var id = detailsObject.id;
//Querying Content Table on detailsObject to obtain correct record
contentQuery.equalTo("descId", detailsObject);
contentQuery.find({
success:function(contentObject){
contentObject[0].set("offer", offer);
contentObject[0].save(null, {
success: function (result){
//alert("offer saved successfully");
document.location.reload(true);
}, error:function(error){
alert("unable to save offer");
}
});
},error: function(error){
alert("Error "+ error.message);
}
});
},
error: function(error) {
alert(error.code + " , " + error.message);
}
});
},
error: function(error) {
alert(error.message);
}
});
So you can see I queried the column "uuid" in the iBeacon class. I am updating based on data entered into an html table by the user. I can update every other column but I can't update my "uuid", I am guessing that as this is part of the query I can't do it this way? I have tried this by finding the object with different parameters and it's that in particular that can't be updated....I need to update this and I'd appreciate any help on it.
FURTHER EDIT
I have been trying out things on this and have since noticed that if I put a hard coded string into where I set the uuid i.e. detailsObject.set("uuid", "UUID EDIT"); this works correctly, however, when I set uuid with the value obtained from the table cell is doesn't proceed. I have debugged it and the correct values are obtained. For testing, I queried the categoryId, when I tried to update the categoryId it wouldn't work either, but if I updated the uuid or any other columns without updating the categoryId, there was no problem.
Using a different editor I get an uncaught TypeError when debugging Uncaught TypeError: Cannot read property 'set' of undefined
One thing to be aware of is that Parse strings are case sensitive. If you store them as lower-case, you need to search using lower-case.
With something like your uuid field you can force the input to lower/upper case before writing it, and then also force user input used for search to lower/upper case as needed.
I have finally solved this myself. This issue was indeed that when searching the query was taking in the edited uuid and not the original uuid, there was a mix up with initialisation with javascript.
So I needed to store the original uuid(which was pulled from parse) as a global string variable. I had stored it incorrectly.
Thank you everyone for your help

Categories