use*_*293 6 javascript firebase
将有关某人的帖子添加到Firebase数据库后,我想将该帖子的引用添加到此人.但是,该人可能已经存在,也可能不存在.
我有:
var ref = new Firebase("https://mydatabase.firebaseio.com/");
var _person = document.getElementById("Person").value;
var _remark = document.getElementById("Remark").value;
var postsRef = ref.child("remarks");
var newPostRef = postsRef.push({
person: _person,
remark: _remark
});
var postID = newPostRef.key();
var personRef = ref.child("person");
personRef.update({
_person: postID
});
Run Code Online (Sandbox Code Playgroud)
但是,这会在子个人中创建一个名为_person的节点,而不是_person变量的值.使用set()会覆盖现有的人.
示例:首先使用子节点person/123456创建节点备注/ -JlkbxAKpQs50W7r84gf
之后我想创建一个节点人员/ 123456(仅当它不存在时),然后添加一个子节点remark/-JlkbxAKpQs50W7r84gf.自动生成post-id(Firebase),但是该人的id将从html表单中获取.
我怎么做?
Sea*_*mus 11
根据您的数据结构,在您之前update,您可能能够获得person您想要的参考.
所以,如果您的数据看起来像这样:
{
"remarks" : {
...
},
"person" : {
"123456" : {
"name" : "foo",
...
"blah" : "bar"
},
...
}
}
Run Code Online (Sandbox Code Playgroud)
并且document.getElementById("Person").value给你123456,你可以获得如下参考:
var personRef = ref.child("person").child(_person);
Run Code Online (Sandbox Code Playgroud)
然后你想看看它是否存在,如果存在,更新它:
personRef.once('value', function(snapshot) {
if( snapshot.val() === null ) {
/* does not exist */
} else {
snapshot.ref.update({"postID": postID});
}
});
Run Code Online (Sandbox Code Playgroud)