javascript - 如何在firebase中存储每个用户的对象列表

标签 javascript firebase firebase-realtime-database

我正在尝试使用 firebase 编写一个应用程序。我想将 JSON 搜索对象存储在 searches/ 中,并将对每个对象的引用存储在属于进行搜索的用户的表中。这是我的尝试:

  var firebase = require("firebase");
  firebase.initializeApp(firebaseConfig);
  var database = firebase.database();

  /*
  * Inserts a search into the database
  */
  this.addSearchToDB = function(positive, negative, neutral){
    let today = new Date();
    let dateCreated = today.getFullYear()+"-"+(today.getMonth()+1)+"-"+today.getDate();
    var search = {
                "query": searchInput,
                "location": location,
                "until": date,
                "dateCreated": dateCreated,
                "amount": tweetAmount,
                "positive": positive,
                "negative": negative,
                "neutral": neutral
                };
    //setup of path to reference the data
    var searchesRef = database.ref("searches");
    var newSearchKey = searchesRef.push(search).key;

    console.log("newSearchRef key:");
    console.log(newSearchKey);

    let user = firebase.auth().currentUser;
    let uid = user.uid;

    console.log("Curr user id: "+uid);

    let userRef = database.ref("users/"+uid);
    let currUserSearches;
    userRef.once("value").then( (value) => {
      currUserSearches = value;
    });

    console.log("Current user searches");
    console.log(currUserSearches);

    if (currUserSearches === undefined)
      currUserSearches = [];

    currUserSearches.push(newSearchKey);

    userRef.set(currUserSearches).then( () => {
      database.ref("users/"+uid).once("value").then((value)=>{
        console.log(value.val());
      });
    });
  }

在第一次插入时,会发生这种情况:

  1. 我得到一个 newSearchKey(成功登录到控制台)
  2. 我获取了 currentUser 的用户 ID(成功登录到控制台)
  3. currUserSearches 未定义。 (将未定义记录到控制台)
  4. userRef.set() 回调中,会找到包含 newSearchKey 的列表并将其打印到控制台。

这一切都很好。这就是我对第一个插入的期望。但是,当我再次插入时,完全相同的过程会重复,这意味着 currUserSearches 再次未定义。这当然是错误的。 currUserSearches 应该包含我刚刚插入的键。但它似乎忘记了我插入的内容。

这里发生了什么,我怎样才能实现我想要的行为?

最佳答案

这是因为对 Firebase 数据库的所有查询(读取和写入)都是异步的。 console.log #3 在 userRef.once("value") 返回结果之前执行。

您应该链接 promise ,如下所示:

let userRef = database.ref("users/"+uid);
let currUserSearches;

userRef.once("value")
.then( (value) => {
  currUserSearches = value;

  if (currUserSearches === undefined)
        currUserSearches = [];

      currUserSearches.push(newSearchKey);

      return userRef.set(currUserSearches);
})
.then( () => {
  return database.ref("users/"+uid).once("value");  // <- Actually could be userRef.once("value") 

})
.then((value)=>{
    console.log(value.val());
});

关于javascript - 如何在firebase中存储每个用户的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50171618/

相关文章:

c# - 如果我添加第二个文本框,Javascript 将无法正常工作

swift - Firebase 数据库通知

javascript - 错误代码 : "auth/internal-error" message: "Photo URL too long." Prototype N

ios - Swift 中的 Firebase。无法将类型 'NSNull' 的值转换为 'NSDictionary'

android - 用户存在和身份验证

javascript - 如何使用 HTML5 音频计算一组轨道的总持续时间?

javascript - Crockford 的 .supplant 多层次对象

javascript - 如何在此 html 表中添加带有动态表值的行跨度?

java - 如何将 int 转换为在 textView 内设置

java - 带有从 firebase 到数据库的数据的 TextView 在屏幕上消失