Я пытаюсь извлечь некоторые данные из базы данных каким-то странным способом.
По сути, я пытаюсь сделать следующее:
- получить всех пользователей БД
- сравнить данные всех пользователей с данными текущих пользователей
- if match - сохранить эти данные в узле "Matches /"
- , а затем извлечь отсортированные данные. (сортировка важна, поэтому я использую forEach, потому что без него я могу получить данные просто отлично.)
Теперь проблема, с которой я сталкиваюсь, заключается в том, что данные извлекаются, сортируются, но получаются несколько раз. времена (количество совпадений * количество совпадений раз), которые, как я полагаю, происходят из-за вложенных циклов forEach. какие-либо предложения о том, как это исправить?
Схема базы данных:
Код:
// Go through all the users and get their names.
var rootRef2 = firebase.database().ref().child("Users");
rootRef2.once("value", function (snapshot) {
snapshot.forEach(function (child) {
// Go to "Arrays/" and get all the "SStrings"
var rootRef3 = firebase.database().ref().child("Arrays/" + child.key);
rootRef3.once("value", function (snapshot) {
var datasnap = snapshot.val();
var SString = datasnap.SString;
var nambe = datasnap.name;
//compare the current_user inputed strings (FinalSongString) with inputed strings of all other users (SString)
var DbMatch = [finalSongString, SString];
//find how many values match
var DbResult = DbMatch.shift().filter(function (v) {
return DbMatch.every(function (a) {
return a.indexOf(v) !== -1;
});
});
//data formating from here **********
var DBindexes = [];
var DBresultArr = [];
DbResult.forEach(function (source) {
DBindexes.push(finalSongString.indexOf(source))
});
for (var i = 0; i < DBindexes.length; i++)
DBresultArr.push(" " + userSongs[DBindexes[i]]);
// only continue is there is a match with someone other than current_user
if (DbResult.length >= 1 && child.key != username) {
for (var i = 0; i < DBresultArr.length; i++) {
DBresultArr[i] = DBresultArr[i].capitalize().replace(/ -/g, " -");
}
// to here **********
// Create node "Matches/" in the database to store the data that matches
var rootRef = firebase.database().ref().child("Matches");
var userMatches =
{
"the_matched": nambe,
"matches": DBresultArr,
"nr_of_matches": DBresultArr.length,
};
rootRef.child(db_name).child(child.key).set(userMatches, function (error) {
if (error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
window.alert("Message:" + errorMessage);
}
else {
//nothing please, just do the if.
}
});
//download the data that is under the Current_User ID (db_name) in the "Matches" node. ordered by number of matches.
const ref = firebase.database().ref('Matches/' + db_name).orderByChild('nr_of_matches')
ref.once('value', function (snapshot) {
snapshot.forEach(function (child) {
const matches = child.val().matches
const nr_of_matches = child.val().nr_of_matches
const the_matched = child.val().the_matched
console.log("matches : " + matches)
document.getElementById("ppl").style.visibility = "visible";
counter++;
console.log(counter)
if (nr_of_matches == 1) {
document.getElementById("f1").innerHTML += " <br><br><br><br><br><br><br><br></br> <span class='counter'> #" + counter + "</span> <br><br><br><br><br><br><br><br><span class='name'>" + the_matched + "</span>" +
"<br>" + "<span class='common'> You have </span>" + "<span class='common'>" + nr_of_matches +
"</span>" + "<span class='common'>song in common:</span><br><br><br> <span class='common2'>" +
matches + "</span><br><br><br><br><br><br><br><br><br><br><br><br><br>";
}
else if (nr_of_matches >= 2) {
document.getElementById("f1").innerHTML += " <br><br><br><br><br><br><br><br></br> <span class='counter'> #" + counter + "</span> <br><br><br><br><br><br><br><br><span class='name'>" + the_matched + "</span>" +
"<br>" + "<span class='common'> You have </span>" + "<span class='common'>" + nr_of_matches +
"</span>" + "<span class='common'>songs in common:</span> <br><br><br> <span class='common2'>" +
matches + "</span><br><br><br><br><br><br><br><br><br><br><br><br><br>";
}
});
});
}
})
});
});