Firebase: how to generate a unique numeric ID for key? - push

I need numeric IDs for human readability. How do I get it in Firebase?
I want numeric ID for keys, e.g. "000000001", "000000002","00000003","00000004".
The reason I need it is because these IDs will become the permanent object ID both online and offline. I want users to be able to browse that object page by just entering URL "/objects/00000001" without efforts.
I am asking here, because I want to know if this can be done without using .priority, sub-properties, etc. I guess set method can do it somehow. If it is not possible, just tell me no, I can accept that answer.

I'd suggest reading through the Firebase documentation. Specifically, see the Saving Data portion of the Firebase JavaScript Web Guide.
From the guide:
Getting the Unique ID Generated by push()
Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it. The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push({
author: "gracehop",
title: "Announcing COBOL, a New Programming Language"
});
// Get the unique ID generated by push() by accessing its key
var postID = newPostRef.key;
Source: https://firebase.google.com/docs/database/admin/save-data#section-ways-to-save
A push generates a new data path, with a server timestamp as its key. These keys look like -JiGh_31GA20JabpZBfa, so not numeric.
If you wanted to make a numeric only ID, you would make that a parameter of the object to avoid overwriting the generated key.
The keys (the paths of the new data) are guaranteed to be unique, so there's no point in overwriting them with a numeric key.
You can instead set the numeric ID as a child of the object.
You can then query objects by that ID child using Firebase Queries.
From the guide:
In JavaScript, the pattern of calling push() and then immediately calling set() is so common that we let you combine them by just passing the data to be set directly to push() as follows. Both of the following write operations will result in the same data being saved to Firebase:
// These two methods are equivalent:
postsRef.push().set({
author: "gracehop",
title: "Announcing COBOL, a New Programming Language"
});
postsRef.push({
author: "gracehop",
title: "Announcing COBOL, a New Programming Language"
});
Source: https://firebase.google.com/docs/database/admin/save-data#getting-the-unique-key-generated-by-push

As explained above, you can use the Firebase default push id.
If you want something numeric you can do something based on the timestamp to avoid collisions
f.e. something based on date,hour,second,ms, and some random int at the end
01612061353136799031
Which translates to:
016-12-06 13:53:13:679 9031
It all depends on the precision you need (social security numbers do the same with some random characters at the end of the date). Like how many transactions will be expected during the day, hour or second. You may want to lower precision to favor ease of typing.
You can also do a transaction that increments the number id, and on success you will have a unique consecutive number for that user. These can be done on the client or server side.
(https://firebase.google.com/docs/database/android/read-and-write)

Adding to the #htafoya answer.
The code snippet will be
const getTimeEpoch = () => {
return new Date().getTime().toString();
}

As the docs say, this can be achieved just by using set instead if push.
As the docs say, it is not recommended (due to possible overwrite by other user at the "same" time).
But in some cases it's helpful to have control over the feed's content including keys.
As an example of webapp in js, 193 being your id generated elsewhere, simply:
firebase.initializeApp(firebaseConfig);
var data={
"name":"Prague"
};
firebase.database().ref().child('areas').child("193").set(data);
This will overwrite any area labeled 193 or create one if it's not existing yet.

https://firebase.google.com/docs/firestore/manage-data/transactions
Use transactions and keep a number in the database somewhere that you can increase by one. This way you can get a nice numeric and simple id.

Related

Firestore - saving external links in a document with both url and title

How can I create an array in firestore that can save external links?
I want to save the title and the href so that I can use both values in the read.
I want the links attribute to be an array so that I can save multiple links. Is it possible to do that in a single firebase attribute, or should I create separate link attributes with a href and title for each one (ie firstLinkTitle, firstLinkHref)?
It's not possible to have a number of links, that would be a different array - similar to an array of arrays.
The possibility for the creation of a field of type array for your documents, you can either use the console, where this type is available or via code as the following example:
const data = {
stringExample: 'Example',
arrayExample: ['Title', 'href']
};
const res = await db.collection('data').doc('one').set(data);
With the above example, you should be able to create a field of type array and set the data to it.
Besides that, if you want to update data from your array without uploading all the data again, you can use the function arrayUnion() or use the arrayRemove(), to remove elements from it.
You can get more information on how to work with arrays in Firestore, by checking the below documentation.
Add Data
In case you need something like nested arrays, indeed, you will need to have a "child" collection that will be linked to the father one.
Let me know if the information helped you!

How to use Moodle REST API Call mod_data_add_entry (and parameters)?

I'm trying to set up a webpage that communicates with a Moodle page. I need different data from a database activity and want to create new entries. Note that I am not talking about the SQL database in BG, it is the activity database in courses.
The information should be retrieved/transferred via the REST API, an HTML POST Request. My problem is that I don't know how to add a new record to the database activity because I cannot transfer the data array. Only the first parameter given appears in my database.
E.g. i tried ...&wsfunction=mod_data_add_entry&databaseid=10&data[0][fieldid]=66&data[0][value]=12&data[1][fieldid]=67&data[1][value]=test
And many other combinations. Always only the first parameter is shown in the database.
The docs tell me this (Pseudocode):
//The fields data to be created
list of (
object {
fieldid int //The field id.
subfield string Default to "" //The subfield name (if required).
value string //The contents for the field always JSON encoded.
}
)
Alternatively:
REST (POST parameters)
data[0][fieldid]= int
data[0][subfield]= string
data[0][value]= string
I cannot find anywhere else something called a "subfield".
Any ideas?
Okay, found it. You have to put your values in "", unless they are not a number. Seems like there is a connection with this special activity because you don't have to do it elsewhere.

Using childByAutoId On Single Value?

I am pretty new to both Swift and Firebase, and I am attempting to make a simple app using Firebase as the backend. As far as I know, there is no memory-efficient way to use the numChildren() function without loading every single child into memory for counting, so I am implementing my own simple counter for the number of "Events" that have been created in my app.
The documentation for Firebase states that the childByAutoID() method should be used for updating lists in multi-user applications. I am assuming it adds a timestamp to the requested update and does them in order.
My question is whether it is necessary to use childByAutoID() when only updating a SINGLE field in a multi-user application. That is, will there be conflicts on my numEvents field if I do:
dbRef = FIRDatabase.database().reference()
dbRef.child("numEvents").setValue(num)
Or must I do:
dbRef = FIRDatabase.database().reference()
dbRef.child("numEvents").childByAutoId().setValue(num)
In order to avoid write conflicts? My only real confusion is that the documentation for childByAutoID stresses that it is useful when the children are a list of items, but mine is only a single item.
If you are only updating a single field you should not be using childByAutoId. To update a child value for an object, you need to obtain a reference to that object somehow, perhaps by a query of some sort (in many cases you will naturally already have a reference to the object if it needs to be changed) and you can change the value like this:
dbRef.child("events").child(objectToUpdateId).child(fieldToUpdateKey).setValue(newValue)
childByAutoId in this context would be used to create a new field like:
dbRef.child("events").childByAutoId().setValue(newObject)
I'm not exactly sure how this applies to your situation, but those are some descriptions of how to update a field, and use childByAutoId.
What childByAutoId does is create a unique key for a node, to avoid using the same key multiple times and then creating data conflicts like inconsistency (not write conflicts) to avoid write conflicts you use the transaction blocks.
The best way to learn is to try it out
If num == 1 , in the first example the result will be
dbRef:{
numEvents:1
}
While the second will be
dbRef:{
numEvents:{
//The auto-generated key
KLBHJBjhbjJBJHB:1
}
}
The childByAutoId would be useful if you want to save in a node multiple children of the same type, that way each children will have its own unique identifier
For example
pet:{
KJHBJJHB:{
name:fluffy,
owner:John Smith,
},
KhBHJBJjJ:{
name:fluffy,
owner:Jane Foster,
}
}
This way you have a unique identifier for cases where there is no clear way with the item data to guarantee it will be unique (in this case the pet's name)
Few things here:
childByAutoId is not a timestamp. But is used to create unique nodes in any given node.
Use case of childByAutoId :
You have messages node which stores messages from multiple user who are involved in a group chat. So each user can add messages in the group chat so you would do something like this each time user sends message:
dbRef = FIRDatabase.database().reference()
dbRef.child("messages").childByAutoId().setValue(messageText)
So this will create a unique message id for each message from different users. This will kind of act like primary key of message in normal databases.
The structure of database will be something like this:
messages: {
"randomIdGenerated-12asd12" : "hello",
"randomIdGenerated-12323D123" : "Hi, HOw are you",
}
So in your case your first approach is good enough! Since you dont need unique node for counting number of events added.

How to save one value of Parse object without overwriting entire object?

I have two users accessing the same object. If userA saves without first fetching the object to refresh their version, data that userB has already successfully saved would be overwritten. Is there any way(perhaps cloud code?) to access and update one, and only one, data value of a PFObject?
I was thinking about pushing the save out to the cloud, refreshing the object once it gets there, updating the value in the cloud, and then saving it back. However that's a pain and still not without it's faults.
This seems easy enough, but to me was more difficult than it should have been. Intuitively, you should be able to filter out the fields you don't want in beforeSave. Indeed, this was the advice given in several posts on Parse.com. In my experience though, it would actually treat the filtering as deletions.
My goal was a bit different - I was trying to filter out a few fields and not only save a few fields, but translating to your context, you could try querying the existing matching record, and override the new object. You can't abort via response.failure(), and I don't know what would happen if you immediately save the existing record with the field of interest and null out the request.object property - you could experiment on your own with that:
Parse.Cloud.beforeSave("Foo", function(request, response) {
// check for master key if client is not end user etc (and option you may not need)
if (!request.master) {
var query = new Parse.Query("Foo");
query.get(request.object.id).then(function(existing) {
exiting.set("some_field", request.object.get("some_field"));
request.object = exiting; // haven't tried this, otherwise, set all fields from existing to new
response.success();
}, function(error) {
response.success();
});
}
});

How to change live date?

I wonder, How do I change a live data schema with MongoDB ?
For example If I have "Users" collection with the following document:
var user = {
_id:123312,
name:"name",
age:12,
address:{
country:"",
city:"",
location:""
}
};
now, in a new version of my application, if I add a new property to "User" entity, let us say weight, tall or adult ( based on users year ), How to change all the current live data which does not have adult property. I read MapReduce and group aggregation command but, they seem to be comfortable and suitable for analytic operation or other calculations, or I am wrong.
So what is the best way to change your current running data schema in MongoDB ?
It really depends upon your programming language. MongoDB is really good at having a dynamic schema. I think your pattern of thought at the moment is too SQL related whereby you believe that all rows, even if they do not yet have a value, must have the new field.
The reality is quite different. The rows which have nothing meaningful to put into them do not require the field and you can, in your application, just check to see if the returned document has a value, if not then you can assume, as in a fixed SQL schema, that the value is null.
So this is one aspect where MongoDB shines, is the fact that you don't have to apply that new field to the entire schema on demand, instead you can lazy fill it as data is entered by the user.
So just code the field into your application and let the user do the work for you.
The best way to add this field is to write a loop, in maybe the console close or on the primary of your replica (if you have one, otherwise just on the server), like so:
db.users.find().forEach(function(doc){
doc.weight = '44 stone';
db.users.save(doc);
});
That is currently the best way to do something like what your asking.