firebase数据库推送方法使用唯一键向数据库子项添加对象,例如, postsRef.push({ author: "gracehop", title: "Announcing COBOL, a New Programming Language"}); 在数据库中放置如下内容 "posts": { "-JRHTHaIs-jNPLXOQi
postsRef.push({
author: "gracehop",
title: "Announcing COBOL, a New Programming Language"
});
在数据库中放置如下内容
"posts": {
"-JRHTHaIs-jNPLXOQivY": {
"author": "gracehop",
"title": "Announcing COBOL, a New Programming Language"
}
但是,如果我将push方法与对象数组一起使用,例如
postsRef.push({
{
author: "gracehop1",
title: "Announcing COBOL, a New Programming Language"
},
{
author: "gracehop2",
title: "Announcing COBOL, a New Programming Language"
}});
我在数据库中获得了一个具有枚举对象的唯一键,即
"posts": {
"-JRHTHaIs-jNPLXOQivY": {
"0": {
"author": "gracehop1",
"title": "Announcing COBOL, a New Programming Language"
},
"1": {
"author": "gracehop2",
"title": "Announcing COBOL, a New Programming Language"
}
}}
有没有办法在单个事务中推送一个对象数组,这样我就可以获得数组中每个对象的唯一键,即结果看起来像
"posts": {
"-JRHTHaIs-jNPLXOQivY": {
"author": "gracehop1",
"title": "Announcing COBOL, a New Programming Language"
"-JRHTHaIs-jNPLXOQivZ": {
"author": "gracehop2",
"title": "Announcing COBOL, a New Programming Language"
}
}}
一个鲜为人知的事实是你可以在没有任何参数的情况下调用push(),它只会为你生成一个位置/推送ID.通过该位置和多位置更新(请参阅
here和
here),您可以执行以下操作:
var key1 = postsRef.push().key;
var key2 = postsRef.push().key;
var updates = {};
updates[key1] = {
author: "gracehop1",
title: "Announcing COBOL, a New Programming Language"
};
updates[key2] = {
author: "gracehop2",
title: "Announcing COBOL, a New Programming Language"
};
ref.update(updates);
