Firebase db.ref 不是一个函数(node.js)
2022-07-24
586
在我返回 MongoDB 之前,有人能告诉我我的代码中有什么错误吗?
项目采用 Node.js(Next.js)
这是我设置 firebase 的方式(例如,它适用于使用 Google 登录进行身份验证):
import { initializeApp } from 'firebase/app';
const credentials = {
...
}
const firebase = initializeApp(credentials);
export default firebase;
然后这是我的 api js 文件,它抛出错误“db.ref”不是函数:
import firebase from '@/firebase/firebase'
import { getDatabase, ref, onValue, update, child, orderByChild, equalTo, once } from "firebase/database"
export default async (req, res) => {
const db = getDatabase(firebase);
if (req.method === 'POST') {
const body = req.body
const playlistTracks = body.playlist
const playlistName = body.name
const uid = body.uid
const data = ...
console.log(data)
var ref = db.ref().child('users');
ref.child(uid).orderByChild('n').equalTo(playlistName).once("child_added", function(snapshot) {
let listId = snapshot.key;
db.ref("users/" + uid + "/" + listId).update(data);
res.send({ risp : 'ok' })
});
}
}
实时数据库结构是:
- users
- <user uid>
- <playlist uid>
c: []
n: "playlist name"
所以我尝试首先通过名称(“n”值)检索正确的播放列表,将所有“n”与给定播放列表的名称进行比较,然后我需要用我的对象(数据)更新(覆盖)它
更新:
因此,我在文档中找到了其他方法 Web 版本 9(模块化),正如 Frank van 所建议的那样下面的 Puffelen,但现在它抛出一个错误
@firebase/database: FIREBASE WARNING: Exception was thrown by user callback. Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
我的代码现在是这样的:
try {
const myQuery = query(ref(db, 'users/' + uid), orderByChild('n'), equalTo(playlistName));
onChildAdded(myQuery, (data) => {
let listId = data.key;
const updates = {};
updates["users/" + uid + "/" + listId] = dataToUpdate;
update(ref(db), updates);
}, {
onlyOnce: true
});
res.send({ risp : 'ok' })
} catch (e) {
res.status(400).end();
}
也尝试过这样,但还是同样的错误:
const myQuery = query(ref(db, 'users/' + uid), orderByChild('n'), equalTo(playlistName));
onChildAdded(myQuery, (data) => {
let listId = data.key;
update(ref(db, "users/" + uid + "/" + listId), dataToUpdate)
.then(() => {
res.send({ risp: 'ok' })
})
.catch((error) => {
res.status(400).end();
});
}, {
onlyOnce: true
});