Discord.js Role Assign and Looping Issues - javascript

I am not very efficient with my code which may be the reasons why this keeps failing. I am trying to remove and assign roles to "verified" users. The basic gist of the code is to loop through all "verified" users and assign them appropriate roles according to the data received from the API.
const fetch = require("node-fetch");
var i = 0;
function mainLoop(
guild,
redisClient,
users,
main_list,
Pilot,
Astronaut,
Cadet,
main_guild,
cadet_guild,
guest
) {
setTimeout(function () {
redisClient.GET(users[i], async function (err, reply) {
if (reply != null) {
var json = await JSON.parse(reply);
var uuid = Object.keys(json).shift();
if (Object.keys(main_list).includes(uuid)) {
var tag = users.shift();
var rank = main_list[uuid];
console.log(`${tag}: ${rank}`);
var role = guild.roles.cache.find(
(role) => role.name === `| ✧ | ${rank} | ✧ |`
);
await guild.members.cache.get(tag).roles.remove(guest);
await guild.members.cache.get(tag).roles.remove(Astronaut);
await guild.members.cache.get(tag).roles.remove(Cadet);
await guild.members.cache.get(tag).roles.remove(Pilot);
await guild.members.cache.get(tag).roles.remove(cadet_guild);
await guild.members.cache.get(tag).roles.add(main_guild);
await guild.members.cache.get(tag).roles.add(role);
} else {
var tag = users.shift();
console.log(`${tag}: Guest`);
await guild.members.cache.get(tag).roles.remove(Astronaut);
await guild.members.cache.get(tag).roles.remove(Cadet);
await guild.members.cache.get(tag).roles.remove(Pilot);
await guild.members.cache.get(tag).roles.remove(main_guild);
await guild.members.cache.get(tag).roles.remove(cadet_guild);
await guild.members.cache.get(tag).roles.add(guest);
}
}
i++;
if (i < users.length) {
mainLoop(
guild,
redisClient,
users,
main_list,
Pilot,
Astronaut,
Cadet,
main_guild,
cadet_guild,
guest
);
}
});
}, 5000);
}
The code will fetch api data, map the "verified" users and api data into an array. Then, when it starts looping through the users array, it will only log 3 times and not assign any roles. Any help would be appreciated.
I can provide extra explanation/code if needed.

One possible issue I see here is that you are both incrementing the index i and calling .shift() on the users array. This may be the cause of the problem you are experiencing, as this will entirely skip some of the users in the array. Array.shift() doesn't just return the first element of the array; it removes it from the array.
Consider, for example, that your users array looks like this:
var users = ["Ted", "Chris", "Ava", "Madison", "Jay"];
And your index starts at 0 like so:
var i = 0;
This is what is happening in your code:
Assign roles for users[i]; the index is currently 0, so get users[0] (Ted).
Get Ted's tag via users.shift(). users is now: ["Chris", "Ava", "Madison", "Jay"]
Increment the index with i++. i is now: 1.
Assign roles for users[i]; the index is currently 1, so get users[1] (now Ava, skips Chris entirely).
Get Ava's tag via users.shift() (actually gets Chris' tag). users is now: ["Ava", "Madison", "Jay"]
Increment the index with i++. i is now: 2.
Assign roles for users[i]; the index is currently 2, so get users[2] (now Jay, skips Madison entirely).
And so on, for the rest of the array; about half of the users in the users array will be skipped.
I don't know how many users are supposed to be in your users array, but this could be the reason why so few logs are occurring. Note, however, that this is just one cause of the problem you are experiencing; it is possible that there are more reasons why you are having that issue, such as rate limits.
My recommendation on how to fix this is to not use users.shift() to get the user's tag. Simply use users[i], which will return the proper tag value without messing with the length of the array. Another way to fix this would be to remove the index incrementation, and always use 0 as your index. Use one or the other, but not both.

Related

Missing updated record when using map function

This is my code for update many records with mongodb.
const nfts = await waxModel.find();
console.log(nfts.length) // -> 121
// Option 1: using map()
nfts.map(async nft => {
nft.trait_attribute = null;
await nft.save();
});
// Option 2: using loop
for (let i = 0; i < nfts.length; i++) {
nfts[i].trait_attribute = null;
await nfts[i].save();
}
This is my DB, no recored have trait_attribute: null:
This is the first result when I use map(), only have 2 records:
And this is the second result when I use for loop:
I don't know that is the problem. In my previous question: I know map methods don't handle the asynchronous function but it's still have full records not missing many updated records as now.
Thank for your attention.
It looks like your code doesn't handle race conditions well.
The first option saves every nft simultaneously whilst the second one saves them one at a time. A more readable way to do that would be using a for-of loop:
for (const nft of nfts) {
nft.trait_attribute = null;
await nft.save();
}

Multiple Firebase listeners in useEffect and pushing new event into state

I want to retrieve a list of products in relation to the user's position, for this I use Geofirestore and update my Flatlist
When I have my first 10 closest collections, I loop to have each of the sub-collections.
I manage to update my state well, but every time my collection is modified somewhere else, instead of updating my list, it duplicates me the object that has been modified and adds it (updated) at the end of my list and keep the old object in that list too.
For example:
const listListeningEvents = {
A: {Albert, Ducon}
B: {Mickael}
}
Another user modified 'A' and delete 'Ducon', I will get:
const listListeningEvents = {
A: {Albert, Ducon},
B: {Mickael},
A: {Albert}
}
And not:
const listListeningEvents = {
A: {Albert},
B: {Mickael},
}
That's my useEffect:
useEffect(() => {
let geoSubscriber;
let productsSubscriber;
// 1. getting user's location
getUserLocation()
// 2. then calling geoSubscriber to get the 10 nearest collections
.then((location) => geoSubscriber(location.coords))
.catch((e) => {
throw new Error(e.message);
});
//Here
geoSubscriber = async (coords) => {
let nearbyGeocollections = await geocollection
.limit(10)
.near({
center: new firestore.GeoPoint(coords.latitude, coords.longitude),
radius: 50,
})
.get();
// Empty array for loop
let nearbyUsers = [];
// 3. Getting Subcollections by looping onto the 10 collections queried by Geofirestore
productsSubscriber = await nearbyGeocollections.forEach((geo) => {
if (geo.id !== user.uid) {
firestore()
.collection("PRODUCTS")
.doc(geo.id)
.collection("USER_PRODUCTS")
.orderBy("createdDate", "desc")
.onSnapshot((product) => {
// 4. Pushing each result (and I guess the issue is here!)
nearbyUsers.push({
id: product.docs[0].id.toString(),
products: product.docs,
});
});
}
});
setLoading(false);
// 4. Setting my state which will be used within my Flatlist
setListOfProducts(nearbyUsers);
};
return () => {
if (geoSubscriber && productsSubscriber) {
geoSubscriber.remove();
productsSubscriber.remove();
}
};
}, []);
I've been struggling since ages to make this works properly and I'm going crazy.
So I'm dreaming about 2 things :
Be able to update my state without duplicating modified objects.
(Bonus) Find a way to get the 10 next nearest points when I scroll down onto my Flatlist.
In my opinion the problem is with type of nearbyUsers. It is initialized as Array =[] and when you push other object to it just add new item to at the end (array reference).
In this situation Array is not very convenient as to achieve the goal there is a need to check every existing item in the Array and find if you find one with proper id update it.
I think in this situation most convenient will be Map (Map reference). The Map indexes by the key so it is possible to just get particular value without searching it.
I will try to adjust it to presented code (not all lines, just changes):
Change type of object used to map where key is id and value is products:
let nearbyUsersMap = new Map();
Use set method instead of push to update products with particular key:
nearbyUsersMap.set(product.docs[0].id.toString(), product.docs);
Finally covert Map to Array to achieve the same object to use in further code (taken from here):
let nearbyUsers = Array.from(nearbyUsersMap, ([id, products]) => ({ id, products }));
setListOfProducts(nearbyUsers);
This should work, but I do not have any playground to test it. If you get any errors just try to resolve them. I am not very familiar with the geofirestore so I cannot help you more. For sure there are tones of other ways to achieve the goal, however this should work in the presented code and there are just few changes.

Async function inside for loop

I am building an App and I have a problem inside a for loop.
Inside my function I got two arrays as arguments (payload.data.start and payload.data.end) and I am trying to push it inside the mongodb.
My code looks like this
async function emplaceAval (state, payload, blockInfo, context) {
for(var i=0 ; i<payload.data.start.length ; i++) // start and end have the same length
{
const user =await User.findOne({ 'account': payload.data.account })
user.availability.push({start: new Date(payload.data.start[i]+'Z') , end: new Date(payload.data.end[i]+'Z')});
await user.save();
}
}
The problem is that lots of times I lose data. By losing data I mean that the i changes before user.save take place.
I consider to use forEach , but I have two arrays that need to be save together , so I cant .
The second solution I thought is to create an index array . For example if the length of my arrays is 5 , I will create an indexTable=[0 , 1 , 2 , 3 , 4 ] and I will use asyncForEach to this array. But i dont think that this solution is the preferable.
Any ideas? Thanks in advance
From what I can see here the looping is completely unneccesary. MongoDB has a $push operator which allows update of an array without retrieving the document first. This also has an $each option to allow a list of elements to be "pushed" in the singe update.
In short this is just one request and response to the server to await:
// Transpose to array of objects for update
let availability = payload.data.start.map((e,i) =>
({ start: new Date(e+'Z'), end: new Date(payload.data.end[i] + 'Z') })
);
try {
// Perform the **one** update request
let response = await User.updateOne(
{ 'account': payload.data.account },
{ '$push': { 'availability': { '$each': availability } } }
);
// maybe check the response
} catch(e) {
// do something with any error
}
That's all you need do. No need to "loop" and so much less overhead than going back and forth to the server retrieving a document and making changes then putting the document back.

Recursicely call data in a mongodb with node

I am creating a login system and i want to implement a username system automatically after registration with the user first-name and last-name. Everything is working fine but in the case if the registered user with the same first-name and last-name is already in the system i want to concatenate a incrmental number to it.
Example if : firstname:Badmus Lastname:Kabiru is in the system as badmus.kabiru and the newly registered user is also named so the new user username will be badmus.kabiru.1 the next will be badmus.kabiru.2.
My code sample are.
assignUserTrendname: function(req_username, callback){
let userNewname = fetchUserName(req_username);
let inc = 1, newlyAssignUsername;
userNewname.then((usernames) => {
console.log(req_username+" ...................... "+usernames); //The data from the database is loging out
if (usernames.atusername == null || usernames.atusername == undefined) {
newlyAssignUsername = req_username;
console.log("Assign automaticaly "+ newlyAssignUsername);
} else {
newlyAssignUsername = req_username;
console.log(`Username Result is DB: ${usernames.atusername} Req: ${newlyAssignUsername} Search ${inc}`);
if(usernames.atusername.toString() == newlyAssignUsername.toString()){
console.log("User name exit and inc is "+ inc);
inc++;
newlyAssignUsername = `${req_username}.${inc}`;
console.log("New search..."+ newlyAssignUsername);
fetchusernames(newlyAssignUsername); // These is not fetching from the database
}
newlyAssignUsername = `${req_username}.${inc}`;
}
console.log("Assigned is ......"+ newTrendname);
callback(null, newTrendname);
})
.catch((err)=> {console.log(err); throw err;});
}
function fetchUserName(trendname){
return Trender.getUserByTrendname(trendname);
}
If i am taking the wrong route please let me know.
Thanks.
In the scenario that your.username already exists you can search your Users with a regex pattern: ((?:your\.username)\d+$). This will get all records that match: your.username{num} where {num} is any number. If your username's are formatted as your.username.123 the pattern would be: ((?:your\.username\.)\d+$).
Assuming this returns an array, existing_users, you can count the records, since you'll always be incrementing by one, which will give you your next incremented number. Pseudo code:
let inc = existing_users.length + 1;
However, in the scenario that you delete a user your count is going to be off. You would need to loop over your existing_users and extract the number at the end and only keep the largest number.
let largest_num = 0;
existing_users.forEach(user => {
let num = user.match(/\d+$/);
if ( num != null && parseInt(num[0]) > largest_num ) {
largest_num = num[0];
}
});
Then you could do the same as above: let inc = largest_num + 1 and add that to your your.username string.
I do not know what library/framework you're using to search your MongoDB so I cannot write a query and function snippet.
We cannot write your code for you. A general regex has already been given that could be a potential way to solve your problem. If you go that route you can make use of the $regex operator. If you were to store the increment of the username as a separate field you could also sort by that to get the max value as well.
Here is an example of that:
db.users.find({
username: {
$regex: < Your Regex Here >
}
}).sort({
usernameIncrement: -1
}).limit(1);
Please see:
http://mongoosejs.com/docs/queries.html
https://docs.mongodb.com/manual/reference/operator/query/regex/
https://docs.mongodb.com/manual/reference/method/cursor.sort/

Firebase database delete all nodes equalTo a particular value

I have a list of users, which contains a node called scannedCards, which contains an array of cardIds. Below is a screenshot of one user.
There are multiple users like above, I want to delete all the card Ids if they are equalTo(Some Card Id), I want to this with all the users at once.
Below is the query I a using:
const ref = database.ref('users');
const query = ref.orderByChild('cardId').equalTo(cardId);
But the result is always empty, Can someone please tell how I can achieve this?
The query you listed above doesn't seem to be returning anything because, based on the screenshot provided, cardId isn't a direct child property of users, but rather a property of each object under the scannedCards list that users may have.
If you only need to do this as part of a one-time operation, you may run something like this:
const ref = database.ref('users');
ref.once('value').then(snapshot => {
const users = snapshot.val();
for (var user_id in users) {
const scannedCards = users[user_id].scannedCards;
for (var card in scannedCards) {
if (scannedCards[card].card_id == "<some card id>") {
firebase.database().ref(`users/${user_id}/scannedCards/${card_id}`)
.set(null);
}
}
}
});
If you plan on letting logged-in users delete their scanned cards, it would be a little bit less complicated:
// user_id is for whoever is logged in
const ref = firebase.database().ref(`users/${user_id}/scannedCards`);
ref.once('value').then(snapshot => {
const scannedCards = snapshot.val();
for (var card in scannedCards) {
if (scannedCards[card].card_id == "<some card id>") {
firebase.database().ref(`users/${user_id}/scannedCards/${card_id}`)
.set(null)
}
}
});
Also worth pointing out, scannedCards is not an array of card ids, because the keys are object ids and the values are objects (which contain cardId and userId properties).

Categories