В моем чате 1 на 1 я пытаюсь связать свои идентификаторы пользователей. Я создал глобальный чат с моей базой данных, похожей на изображение ниже.

Этот код позволяет мне выполнять поиск по идентификатору пользователя в базе данных firebase, а затем извлекать html-файл личных сообщений, где два пользователя будут иметь приватный чат.
oneOnone.addEventListener('click', function(e){
// Attach an asynchronous callback to read the data at our posts reference
ref.on("value", function (snapshot) {}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
ref.orderByChild("userId").on("child_added", function (snapshot) {
console.log(snapshot.val().userId);
console.log(searchId);
if(searchId.value === snapshot.val().userId){
window.location.href = 'privatemessage.html';
}
});
});
Я склоняюсь к чему-то подобному для разговора один на один
var pmChat = database.ref('chat/' + userId);
Я хотел бы создать новую ссылку, а затем добавить первый идентификатор пользователя, а затем добавить второй идентификатор пользователя или даже отображаемое имя.
Как получить идентификатор или отображаемое имя, которое я ищу, и затем вести эти два чата, а когда каждый раз, когда пользователь выполняет поиск, создавать новый узел для чата каждого пользователя? И если пользователь говорит с тем же человеком, он возвращается в этот чат?
Обновление
Я изменил код, чтобы он выглядел следующим образом
oneOnone.addEventListener('click', function(e) {
// Attach an asynchronous callback to read the data at our posts reference
ref.on("value", function(snapshot) {}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});
ref.orderByChild("userId").on("child_added", function(snapshot) {
console.log(snapshot.val().userId);
if (searchId.value === snapshot.val().userId) {
var currentUser = database.ref('chat').child(userId).child(searchId.value);
var otherUser = database.ref('chat').child(searchId.value).child(userId);
messageForm.addEventListener("submit", function(e) {
e.preventDefault();
var user = auth.currentUser;
var userId = user.uid;
if (user.emailVerified) {
// Get the message the user entered
var message = messageInput.value;
var myPassword = "11111";
var myString = CryptoJS.AES.encrypt(message, myPassword);
// Decrypt the after, user enters the key
var decrypt = document.getElementById('decrypt')
// Event listener takes input
// Allows user to plug in the key
// function will decrypt the message
decrypt.addEventListener('click', function(e) {
e.preventDefault();
// Allows user to input there encryption password
var pass = document.getElementById('password').value;
if (pass === myPassword) {
var decrypted = CryptoJS.AES.decrypt(myString, myPassword);
document.getElementById("demo3").innerHTML = decrypted.toString(CryptoJS.enc.Utf8);
}
});
// Create a new message and add it to the list.
if (userId) {
currentUser.push({
displayName: displayName,
userId: userId,
pic: userPic,
text: myString.toString(),
timestamp: new Date().getTime(), // unix timestamp in milliseconds
})
.then(function() {
messageStuff.value = "";
})
.catch(function(error) {
windows.alert("Your message was not sent!");
messageStuff;
});
} else {
otherUser.push({
displayName: displayName,
userId: userId,
pic: userPic,
text: myString.toString(),
timestamp: new Date().getTime(), // unix timestamp in milliseconds
})
.then(function() {
messageStuff.value = "";
})
.catch(function(error) {
windows.alert("Your message was not sent!");
messageStuff;
});
Мне кажется, я не беру другой идентификатор пользователя, потому что это только строковое значение текстового поля.
var currentUser = database.ref('chat').child(userId).child(searchId.value);
var otherUser = database.ref('chat').child(searchId.value).child(userId);
Так я создаю новые ссылки в базе данных Firebase.