vue.js JavaScript Firebase Realtime Database typeError:insert不是函数

7kjnsjlb  于 2023-05-18  发布在  Vue.js
关注(0)|答案(1)|浏览(94)

我无法在Firebase中的实时数据库上推送、设置、更新。代码如下,非常感谢您的帮助。
imports:

import { serverTimestamp, getDatabase, onChildAdded, push, set, update, runTransaction, get, ref as dbRef } from "firebase/database";
import { db } from "@/config/firebaseConfig";

firebaseConfig中的db就是getDatabase(app)
set()抛出错误

async sendMessage() {
   if (this.messageText.trim().length === 0) return;

    const chatRef = dbRef(db, `chats/${this.chatId}`);
    const snapshot = await get(chatRef);

    const newMessageRef = await push(chatRef);

    const newMessageKey = newMessageRef.key;

    const newMessage = {
        id: newMessageKey,
        sender: this.currentUser.uid,
        text: this.messageText.trim(),
        timestamp: serverTimestamp(),
    };

    console.log("newMessageRef:", newMessageRef);
    console.log("newMessage:", newMessage);

    await set(newMessageRef, newMessage);

错误:
caught(in promise)TypeError:新生儿。insert不是IndexMap中函数。ts:147:30在Map上(obj.ts:50:(21)代理。addToIndexes(IndexMap.ts:115:(24)代理。updateImmediateChild(ChildrenNode.ts:156:(38)代理。updateChild(ChildrenNode.ts:180:19)在viewProcessorApplyUserOverwrite(ViewProcessor.ts:486:34)在viewProcessorApplyOperation(ViewProcessor.ts:103:22)在viewApplyOperation(View.ts:213:18)在syncPointApplyOperation(SyncPoint.ts:107:9)在syncTreeApplyOperationHelper_(SyncTree.ts:726:9)(
我试了新旧API。我的规则设置为真,用于读写。

x6yk4ghg

x6yk4ghg1#

错误消息表明传递给set()方法的数据可能存在问题。具体来说,newMessageRef变量似乎不是Firebase实时数据库中某个位置的有效引用。
不要使用newMessageRef作为set()的第一个参数,而是尝试传递chatRef.child(newMessageKey)。这应该在chats/${this.chatId}位置下创建一个具有指定键的新子节点。

async sendMessage() {
if (this.messageText.trim().length === 0) return;

const chatRef = dbRef(db, `chats/${this.chatId}`);
const snapshot = await get(chatRef);

const newMessageRef = push(chatRef);
const newMessageKey = newMessageRef.key;

const newMessage = {
    id: newMessageKey,
    sender: this.currentUser.uid,
    text: this.messageText.trim(),
    timestamp: serverTimestamp(),
};

console.log("newMessageRef:", newMessageRef);
console.log("newMessage:", newMessage);

await set(chatRef.child(newMessageKey), newMessage);

}

相关问题