【发布时间】:2016-12-29 22:58:40
【问题描述】:
问题
我如何(通过单个 HTTP 请求到 REST API)向 Firebase 写入一个 数组 并为每个数组元素指定一个 (非整数)唯一 ID?
数据
我要写的数据如下所示。
数据写入.jsmyArray = [ {"user_id": "jack", "text": "Ahoy!"},
{"user_id": "jill", "text": "Ohai!"} ];
目标
完成后,我希望我的 Firebase 如下所示。
my-firebase.firebaseio.com{
"posts": {
"-JRHTHaIs-jNPLXOQivY": { // <- unique ID (non-integer)
"user_id": "jack",
"text": "Ahoy!"
},
"-JRHTHaKuITFIhnj02kE": { // <- unique ID (non-integer)
"user_id": "jill",
"text": "Ohai!"
}
}
}
我不希望它看起来像下面这样......
my-anti-firebase.firebaseio.com// NOT RECOMMENDED - use push() instead!
{
"posts": {
"0": { // <- ordered array index (integer)
"user_id": "jack",
"text": "Ahoy!"
},
"1": { // <- ordered array index (integer)
"user_id": "jill",
"text": "Ohai!"
}
}
}
I note this page where it says:
[...] 如果所有键都是整数,并且对象中 0 到最大键之间的键中有一半以上具有非空值,则 Firebase 会将其呈现为数组。
代码
因为我想在单个 HTTP 请求中执行此操作,所以我想避免迭代数组中的每个元素,而是想在单个请求中推送一批。
换句话说,我想做这样的事情:
伪代码.jscurl -X POST -d '[{"user_id": "jack", "text": "Ahoy!"},
{"user_id": "jill", "text": "Ohai!"}]' \
// I want some type of batch operation here
'https://my-firebase.firebaseio.com/posts.json'
但是,当我这样做时,我得到的正是我上面描述的我不想要的(即顺序整数键)。
我想避免做这样的事情:
反伪代码.jsfor(i=0; i<=myArray.length; i++;){ // I want to avoid iterating over myArray
curl -X POST -d '{"user_id": myArray[i]["user_id"],
"text": myArray[i]["text"]}' \
'https://my-firebase.firebaseio.com/posts.json'
}
有可能实现我所描述的吗?如果有,怎么做?
【问题讨论】:
标签: api rest firebase firebase-realtime-database