Firebase convert generated ID to numeric ID - javascript

This is an old question but no answers found. Old answers' source links are dead, old functions are deprecated.
I've look at these topics (1, 2) amongst others, and also current Firebase guide.
function writeUserData(name, win, loss) {
firebase.database().ref('users/').push({
name: name,
wins: win,
losses: loss
});
}
I need to pull or somehow convert the unique ID from each push to numeric ID: 1, 2
UPDATE:
Here's what I'm trying to do:
2 users can login at the same time from 2 different browsers.
1st user hits button 'log-in' or 'start' will be written as users/1/{user's attributes} on firebase.
if there's an existing user
(somehow I need to check that on the user-end), the next user hits
'start' will be written as users/2/{user's attributes} on firebase. Else (no existing user), the user will be written as user1. This is where I think I need push instead of set. I can use set to add more users from 1 browser, but if i open the app from another browser/chrome incognito, the app will just reset the existing users.
if a user refreshes or closes the browser, that user will be removed from firebase so another user can log-in.
I've tried different methods (loop, creating new var...) to achieve this.

Rather than .push, try to use .set or .update. In that way you can set your own generated key. But as already suggested, this may not be the best approach.

Related

Creating increment limit

Ok so I am making a like/dislike system for my website and I got it to work. The only problem is, is that a user can like something more than once, how do I stop this? heres my function
function thumbup(uid, s) {
const prevthumbs = s.thumbs
firebase.db.collection('users').doc(uid).update({
thumbs: prevthumbs + 1
})
}
How can I limit the increment to only one?
To limit how often the user can do something, use their UID as the key for the operation.
For example, if you don't have too many users, you can have a field likedBy in the document which is an array of the UIDs of the users who liked this user.
It's a bit unclear how to exactly implement it in your code for me, as you're already writing to a doc(uid), where usually the user is liking a post or something like that.

Djaty - Why the affected users count is not accurate when using `Djaty.setUser()`?

I'm installing Djaty Javascript SDK on one of my projects. It's installed properly now and I'm trying to use Djaty.setUser()
I want to set all possible user information so I'm using Djaty.setUser() into my code at two places. First place to set userId and the second place to set the user logon.
First place:
Djaty.setUser({userId: user.userId})
Second place:
Djaty.setUser({logon: user.username})
When I create a test bug I expect the bug to have only one affected user but actually it has two users now. What's the problem with my code?
First of all, calling Djaty.setUser multiple times will override the contextual user object everytime. For example, calling it in the order you mentioned will lead to an object with only the logon property.
Regarding your problem, the following scenario can lead to it:
if (isUserLogonAvailable) {
Djaty.setUser({logon: user.username});
} else {
Djaty.setUser({userId: user.userId});
}
app.notExistingMethod();
When the isUserLogonAvailable flag is true, the app.notExistingMethod() bug occurrence will have the contextual user as {userId: user.username, logon: user.username} because if the userId doesn't exist, we fallback to the logon. Similarly, when the code is executed again with isUserLogonAvailable flag is false, another bug occurrence will be submitted but the contextual user will be {userId: user.userId, logon: user.userId}.
Now your bug occurrences have two different users:
1- userId: user.username
2- userId: user.userId
And this results in the two affected users you ask about.

Adding Drop Ship PO to Existing Sales Order in NetSuite

I'm needing to create drop ship purchase orders against sales orders within NetSuite that already exist and have one or more drop ship POs created against it. Now, normally through the UI you can just click the "Drop Ship" link on an item line and there you go, but this is being done programmatically with SuiteScript. I thought I had this figured out years ago, but it was years ago, this hasn't come up since, and I can no longer remember what files I may have been working on at the time.
The system won't allow reverting the order to a "Pending Approval" status, so I can't just change statuses around to force the system to create the new POs. I've also tried the following to no success:
soRecord.setCurrentLineItemValue("item", "createpo", "DropShip");
soRecord.setCurrentLineItemValue("item", "povendor", vendorId);
Nothing happens aside from adding the new item lines to the sales order. I've also tried creating a PO with the appropriaate vendor and attaching it to the item line on the sales order with the following, but it also has no effect:
soRecord.setCurrentLineItemValue("item", "createdpo", poId);
Is there something I'm missing? Or have I been embarking on a fool's errand the entire time?
Those fields are read only. This is what I used
var po = nlapiCreateRecord('purchaseorder', {recordmode:"dynamic", soid:<internal id of salesorder>,poentity:<preferred vendor of item>});
We had an issue where our auto-drop ship POs stopped generating on SO creation. In an afterSubmit UE deployed to SOs, gather an array of vendors on the item lines and then filter to remove duplicates. Then add this logic inside of a for-loop where i < length of filtered vendor array:
var createDSPO = record.create({
type: record.Type.PURCHASE_ORDER,
defaultValues: {
soid: <SO internal id>,
shipgroup: 1,
dropship: true,
custid: <SO customer internal ID>,
entity: poVendorArray[i],
poentity: poVendorArray[i]
}
});
createDSPO.save();
FYI, if you inspect the "Drop Ship" link on the SO record, you'll see why I did this. You may be able to figure out another way to do this.

How to update a dataLayer variable?

We initially push an object containing variables to the dataLayer:
dataLayer.push({
'environment': {
'userName': 'abc',
'id': 123,
'clicks': 0
}
});
We now want to increase the value of environment.clicks with every click a user makes.
How to do that? When we push it via
dataLayer.push({
'environment': {
'clicks': 123
}
});
The dataLayer Array may get 10.000s of entries. How to properly update the variable?
The way to update a datalayer variable is to push a variable, either when a "native" GTM event occurs or alongside a custom event. So basically you are it right.
As for your worries that the DL might get to many entries - the dataLayer gets a new entry on every click in any case (GTM adds that itself), so the additional entries for your variable will probably do not matter that much.
If you still want to avoid this you can update a global Javascript variable and use that in GTM. Google Tag Manager has access to all variables on your page (you will still get all the click events in your dataLayer).
The dataLayer also has a set method that allows you to write to the Datalayer directly, which is apparently what you are looking for. You need to acquire your GTM instance and then you can set values:
var gtm = window.google_tag_manager[{{Container ID}}];
gtm.dataLayer.set('balloonsPopped', undefined);
Details are e.g. here in a Bounteous article. You could use this in a custom HTML tag to update the click count before the click event fires your tag.
Also the dataLayer is reset on page load. It would take a hell of a single page app to collect 10 000s of clicks per pageview.
This is tagged Google Analytics. If you plan to track the clicks in GA remember that a GA session expires after 500 clicks, so the results might not be what you expect (also the free version only has only 10M hit per month, click tracking will quickly exhaust this). And of you want to track the number of click in GA then you would need an event or something to track the click, so the number of events is basically the metric you are looking for, or you could create a custom metric and set it to "1" in your GA call (meaning that it will be incremented by one on every call).
Quoting from the documentation:
It's important to note that pushing a variable of the same name as an existing variable to the data layer will cause the existing value to be overwritten by the new value
Simply pushing an entry with the same variable name and the updated value should work.
Couldn't you use a holder? Something like:
var click_value_holder = dataLayer.environment.clicks;
dataLayer.push({
'environment': {
'clicks': (click_value_holder + 1)
}
});

Check if the data is updated

I've made a working chat with meteor and mongodb, but I want to play a sound or something when there is a new message. However, I don't know how to check if data is updated. I could check if there is a new message by counting the messages before and after the update, but I just don't know how to check for an update.
So my question here is: How do I check for an update in the data?
I have a website that needs to pop up a toastr alert whenever a new message arrives. My collection is called "Alerts". This is what I do:
Alerts.find({notified: false}).observeChanges({
added: function(id, doc) {
Alerts.update(id, {
$set: {
notified: true
}
});
toastr.info(foo, bar);
}
});
Whenever a new alert is created whose field "notified" is false, a toastr alert will be created and that alert will be marked as "notified: true".
Alternatively you could do the same thing but create a separate collection of "notifications" that when observed, are removed from the collection as well that are a distinct collection from your chat messages collection.
You could create a tailing cursor on the oplog collection, so you get a new document whenever something (anything!) in the database changes. But that's not really an elegant solution, because that handler would need to process a lot of junk.
It might be better to have the routine which writes the message to the database also inform any currently online users. There is really no good reason to go the detour over the database.

Categories