简体   繁体   English

Firebase按键未定义

[英]Firebase Push Key Undefined

I am looking to get the the key from a firebase push command when using cloud functions. 我希望在使用云功能时从firebase push命令获取密钥。

const params = {
    date: Date.now(),
    movie,
    movieId: movie.id,
    userId: user.uid,
    group: 'home',
    type: 'watched'
};

const pastRef = event.data.adminRef.root.child(`pastActivity/${user.uid}`);

var newPostRef = pastRef.push().set(params);

var postId = newPostRef.key;

console.log(postId); //undefined

The postId however comes back as undefined. 但是postId返回为undefined。 Have try a few other suggested methods without any results. 尝试其他建议的方法但没有任何结果。

Reference.set() returns a void promise that resolves when the write operation completes. Reference.set()返回一个无效承诺,该承诺在写操作完成时解决。 You can't get the key of it. 您无法获得它的钥匙。 Instead, split the push() and set(...) into separate statements, so that you can capture the reference 而是将push()set(...)拆分为单独的语句,以便可以捕获引用

var newPostRef = pastRef.push();
newPostRef.set(params);

var postId = newPostRef.key;

console.log(postId); //undefined

A shorter version can be used if you don't need the newPostRef variable 如果不需要newPostRef变量,可以使用较短的版本

//var newPostRef = pastRef.push().set(params);
//var postId = newPostRef.key;

const newPostRefKey = pastRef.push(params).key
//this pushes the data and returns the key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM