![](/img/trans.png)
[英]Firebase firestore is there a way to write data from an array into a document and then subcollections?
[英]How to push data into subcollections in firebase
我正在使用 react-native 和 firebase 创建一个消息传递应用程序。 它工作得很好。
现在我想通过创建私人聊天更进一步。 据我了解,我需要将数据填充到子集合中。 例如: chats>chatroom1>data
, chats>chatroom2>data etc
我目前正在使用此代码
从“火力基地”导入 firebase;
class Fire {
constructor (props) {
this.init()
this.checkAuth()
}
init = () => {
if (!firebase.apps.length) {
}
};
checkAuth = () => {
firebase.auth().onAuthStateChanged(user => {
if (!user) {
firebase.auth().signInAnonymously();
}
})
}
send = messages => {
messages.forEach(item => {
const message = {
text: item.text,
timestamp: firebase.database.ServerValue.TIMESTAMP,
user: item.name
}
this.db.push(message)
})
}
parse = message => {
const {user, text, timestamp} = message.val();
const {key, _id} = message
const createdAt = new Date(timestamp)
return {
_id,
createdAt,
text,
user
}
}
get = callback => {
this.db.on('child_added', snapshot => callback(this.parse(snapshot)))
}
off() {
this.db.off()
}
get db() {
return firebase.database().ref("messages");
}
get uid(){
return(firebase.auth().currentUser || {}).uid
}
}
如何从此代码填充子集合?
我相信调用特定的子集合firebase.database().ref("messages/chatroomid");
会成功的,对吧?
我所说的子收藏是什么意思
目前我的 JSON 树看起来像:
database
- messages
- mvhhsjsfurhcb
- text: "hi"
timestamp: 9942313949
user: "David"
firebase.database().ref("messages"); calls out the data under messages
这就是我要的
database
- messages
-chatroom1
- mvhhsjsfurhcb
- text: "hi"
timestamp: 9942313949
user: "David"
-chatroom2
- mvhhsjsfurhcb
- text: "hey, this i room2"
timestamp: 9942313949
user: "Sam"
然后对于firebase.database().ref("messages/chatroom1");
仅在 chatroom1 中调出消息。
我打算用这个实现的是为用户创建一个私人聊天
为了让您更深入地了解,如果我要使用 PHP 执行此操作,我将执行SELECT * WHERE chatroom =:chatroom;
我相信答案将与this.db.push(message)
相关。 也许添加另一个“。” 表示推送消息前还有一个分支
如果要将聊天消息推送到特定的聊天室,可以这样做:
this.db.child("chatroomid1").push(message)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.