Need help in Automated userid generation using jquery - javascript

I want to generate a login id automatically. Logic is to take the user's last name and append a number(like 1, then 2 , then 3). system will also check if this user id exist in database. I have cached the database data in a local variable. If the user id is unique, it will be populated in a text box, otherwise it will append a new number. But This process may go for 10 times, if 10 user has same last name. Could anybody provide a simple solution for this. I want this to be done in JQuery.

Let's say John Doe tries to register an account. You need to:
Send 'Doe' to backend via ajax
Execute a query like this to find the greatest Doe* in DB:
SELECT user_id FROM users WHERE surname = 'Doe' ORDER BY added_ts DESC LIMIT 1
If a record is found, extract the number part out of the user id and send it back, if no record is found simply send 0 back
When ajax response arrives, increment the number you get and concatenate it to the surname.
I am assuming you have a record timestamp of some sort to use in the query (added_ts).
Edit: #Jaromanda X 8 pointed correctly that the query might return wrong results and it should be the surname field we need to check.

Related

Hello , I want to remove new users from mongoDB atlas within 2 minutes if they do not verify their phone number , I think TTL is the way

Document Schema
this is my User schema and the isVerified field is being saved to the DB with the initial value if false
the process is the user enters his phone number and then i send a verification token via SMS for the phone number and save both token and the number in the DB, and then when the user enters the verification token he has received i patch the isVerified field to true .
now i want to remove every document that does not turn isVerified to true within 2 minutes of the document creation . i have seen a few code examples but to be honest i dont know how to or where to implement this feature , should it be in the schema or in the document creation process ?
since i dont know where to start or how to start i have not tried it yet
MongoDB supports TTL Indexes So I'd suggest the following
In your schema add an optional field verificationTimeout. For each newly created user set this value to the current timestamp
Create a TLL index on this field with an expireAfterSeconds of your own choice (btw 2 minutes is really short, I'd suggest like 15 minutes or so ...)
Once the user is verified, remove the verificationTimeout field from the document
Alternatively, you can also set the verificationTimeout to a timestamp where you want your unverified user to be removed and use the expireAfterSeconds: 1 to remove the user at set defined timestamp.
So, if the user didn't verify within the given timeslot, the mongodb server will invalidate the document and remove it from the collection. But as specified in the docs, documents won't be invalidated if the don't contain the specified field. So if you remove the verificationTimeout upon verification, the user won't be removed from the collection.
And the nice thing about this: You don't need to care about removing unverfied users in your own code. The only thing you need to do is create the index and set/remove the value. Ie no extra worker that scans through the elements and checks if they already expired ...

mongoose query with different input

I want to check in a db if 'test' exists in a document, in a specific field. If exists, I want to increment it by 1, to look like this 'test-1', and then check again in the db, and repeat until it's not found, than save it there.
I don't have a problem with the increment part, just with the mongoose/mongodb part where I need to re-query with the new value. Is there any way that can be done in the same query, multiple times?
Edited: I want to create a new field based on the name, but I want this field to be unique, because I want to use it as an id.
So, for instance, if I have something like name: 'John Smith' I want to create a new field in my document like this: uniqueId: john-smith, for the same document. The problem is, if another John Smith is inserted in my collection, I want to check if the uniqueId john-smith is available, if not I want to append a -1 to it, so it will look like this john-smith-1, and so on, until a john-smith-(number) is not found, then I will know the id is unique and save it to the document.
One idea would be to use a Model.find() inside of a recursive function with the uniqueId, and repeat until a document is not found. But I was wondering if there might be another way, maybe something less complicated?
mongodb v4.2.3

Better way to refer to entries in firebase

As far as I know, firebase assigns automatically an unique ID to every new entry in the database. However - these ids are really long and not good looking.
Whats more - I have to refer to them somehow, so currently when Im doing a get request, e.g. to get one entry Im doing something like:
/getEntry/L4Cu7UOENIivnB2bgt
And it's fine, since user doesn't see it anyways.
Hovewer, when making routes to every entry in my app, again I have to refer to specific entry by it's id. So e.g. if Im on route of specified element, e.g.:
http://myapp.com/users/L4Cu7UOENIivnB2bgt - it doesn't look very well if not ugly. If I would make my db in e.g. SQL or NoSQL, I would be able to assign an id by myself so it would increase from 1 and so on.
Q: Am I able to change these long id's somehow? It has to be fixable somehow... Thanks.
Yes you can set your own unique key. Say you have unique usernames for each user then you can do
firebase.database().ref('users/' + userName).set({
firstName: name,
email: email,
profile_picture : imageUrl
});
or you can create your own unique ids and use instead. But there is no auto incremental ids.
Using set() overwrites data at the specified location, including any child nodes.

Javascript function taking too long to complete?

Below is a snipet of code that I am having trouble with. The purpose is to check duplicate entries in the database and return "h" with a boolean if true or false. For testing purposes I am returning a true boolean for "h" but by the time the alert(duplicate_count); line gets executed the duplicate_count is still 0. Even though the alert for a +1 gets executed.
To me it seems like the function updateUserFields is taking longer to execute so it's taking longer to finish before getting to the alert.
Any ideas or suggestions? Thanks!
var duplicate_count = 0
for (var i = 0; i < skill_id.length; i++) {
function updateUserFields(h) {
if(h) {
duplicate_count++;
alert("count +1");
} else {
alert("none found");
}
}
var g = new cfc_mentoring_find_mentor();
g.setCallbackHandler(updateUserFields);
g.is_relationship_duplicate(resource_id, mentee_id, section_id[i], skill_id[i], active_ind,table);
};
alert(duplicate_count);
There is no reason whatsoever to use client-side JavaScript/jQuery to remove duplicates from your database. Security concerns aside (and there are a lot of those), there is a much easier way to make sure the entries in your database are unique: use SQL.
SQL is capable of expressing the requirement that there be no duplicates in a table column, and the database engine will enforce that for you, never letting you insert a duplicate entry in the first place. The syntax varies very slightly by database engine, but whenever you create the table you can specify that a column must be unique.
Let's use SQLite as our example database engine. The relevant part of your problem is right now probably expressed with tables something like this:
CREATE TABLE Person(
id INTEGER PRIMARY KEY ASC,
-- Other fields here
);
CREATE TABLE MentorRelationship(
id INTEGER PRIMARY KEY ASC,
mentorID INTEGER,
menteeID INTEGER,
FOREIGN KEY (mentorID) REFERENCES Person(id),
FOREIGN KEY (menteeID) REFERENCES Person(id)
);
However, you can make enforce uniqueness i.e. require that any (mentorID, menteeID) pair is unique, by changing the pair (mentorID, menteeID) to be the primary key. This works because you are only allowed one copy of each primary key. Then, the MentorRelationship table becomes
CREATE TABLE MentorRelationship(
mentorID INTEGER,
menteeID INTEGER,
PRIMARY KEY (mentorID, menteeID),
FOREIGN KEY (mentorID) REFERENCES Person(id),
FOREIGN KEY (menteeID) REFERENCES Person(id)
);
EDIT: As per the comment, alerting the user to duplicates but not actually removing them
This is still much better with SQL than with JavaScript. When you do this in JavaScript, you read one database row at a time, send it over the network, wait for it to come to your page, process it, throw it away, and then request the next one. With SQL, all the hard work is done by the database engine, and you don't lose time by transferring unnecessary data over the network. Using the first set of table definitions above, you could write
SELECT mentorID, menteeID
FROM MentorRelationship
GROUP BY mentorID, menteeID
HAVING COUNT(*) > 1;
which will return all the (mentorID, menteeID) pairs that occur more than once.
Once you have a query like this working on the server (and are also pulling out all the information you want to show to the user, which is presumably more than just a pair of IDs), you need to send this over the network to the user's web browser. Essentially, on the server side you map a URL to return this information in some convenient form (JSON, XML, etc.), and on the client side you read this information by contacting that URL with an AJAX call (see jQuery's website for some code examples), and then display that information to the user. No need to write in JavaScript what a database engine will execute orders of magnitude faster.
EDIT 2: As per the second comment, checking whether an item is already in the database
Almost everything I said in the first edit applies, except for two changes: the schema and the query. The schema should become the second of the two schemas I posted, since you don't want the database engine to allow duplicates. Also, the query should be simply
SELECT COUNT(*) > 0
FROM MentorRelationship
WHERE mentorID = #mentorID AND menteeID = #menteeID;
where #mentorID and #menteeID are the items that the user selected, and are inserted into the query by a query builder library and not by string concatenation. Then, the server will get a true value if the item is already in the database, and a false value otherwise. The server can send that back to the client via AJAX as before, and the client (that's your JavaScript page) can alert the user if the item is already in the database.

How to get the last record of the table and update a column value and insert to the same column with new record using angularJs/Javascript/Jquery

I am working in Web Api & MVC using angularjs for CURD operations,
In my DB I have a table "Accounts" it has a column with Name "ID" which will insert as
1 for first record and 2 for second record etc...
This column values will increment as per the last record in table,
this process should be in client side only.
Thanks in advance
If I understand your question correctly, you want to send next ID from db to client, create a new record on client with that ID and update it in db.
1) All you need to do is to create a empty record in db and send it's id/primary key to the client. This approach has a potential problem that, if the client stops/chooses to cancel the operation, there will be lot of empty records created.
2) Otherwise, you can fetch the last record from client using select max(id) from table and then use id+1 for the new record. The problem with this approach is that when multiple clients try to update db at the same time, all of them will/may have the same id.
3) In order to overcome the problem of (2), you can use locking mechanisms, but thats not how you do it. Its not worth it.
In my opinion, in most of the cases, client doesn't need to know the id of the going to be created record. Once the record is created, you can send it from db.
Once you're within the table, do everything in there. It's faster an easier.
UPDATE table1 SET column = (SELECT DISTINCT MAX(id) FROM Accounts WHERE user = ? GROUP BY id DESC LIMIT 1 ) WHERE user = ?

Categories

Resources