[英]Custom Object for Cloud Firestore in Node.js runs in snapshot.data is not a function error
I'm working on a web application which receives notifications from an Node.js server.我正在开发一个 web 应用程序,它接收来自 Node.js 服务器的通知。 I use Firebase Cloud Firestore as database.
我使用 Firebase Cloud Firestore 作为数据库。 Both peaces of code are in the same js file and I've initialized my database and Firebase admin correctly (other operations work).
两种代码都在同一个 js 文件中,并且我已经正确初始化了我的数据库和 Firebase 管理员(其他操作有效)。 I want to save pulled data from the database in a custom object:
我想将从数据库中提取的数据保存在自定义 object 中:
// define logentry for user
class LogEntryUser {
constructor(token, email){
this.token = token;
this.email = email;
}
getToken(){
return this.token;
}
getEmail(){
return this.email;
}
}
// Firebase data converter
logConverterUser = {
toFirestore: function(logentryuser){
return {
token: logentryuser.token,
email: logentryuser.email
}
},
fromFirestore: function(snapshot, options){
const data = snapshot.data(options);
return new LogEntryUser(data.token, data.email)
}
}
Here is the code for reading the data from the Cloud Firestore:以下是从 Cloud Firestore 读取数据的代码:
db.collection("Users").get().then(function(querySnapshot){
querySnapshot.forEach((doc) => {
db.collection("Users").doc(doc.id).withConverter(logConverterUser).get().then(function(snapshot){
// convert to log object and read token
logentryuser = snapshot.data();
var registrationToken = logentryuser.getToken();
});
});
});
Running this script runs in an error:运行此脚本会出错:
(node:1648) UnhandledPromiseRejectionWarning: TypeError: snapshot.data is not a function at Object.fromFirestore.
I've used the same code in another js project and everything works fine.我在另一个 js 项目中使用了相同的代码,一切正常。 I have no idea how to solve this problem.
我不知道如何解决这个问题。 Can anyone help me?
谁能帮我?
Best wishes keved最美好的祝愿
For some reason the withConverter method is passing the actual data instead of snapshot into fromFirestore function.由于某种原因,withConverter 方法将实际数据而不是快照传递到 fromFirestore function。 Changing fromFirestore as below fixed it for me.
如下更改 fromFirestore 为我修复了它。
// Firebase data converter
logConverterUser = {
toFirestore: function(logentryuser){
return {
token: logentryuser.token,
email: logentryuser.email
}
},
fromFirestore: function(snapshot){
const data = snapshot;
return new LogEntryUser(data.token, data.email)
}
In a Node.js Server you can use a 'normal' Javascript Object to store the snapshot.在 Node.js 服务器中,您可以使用“普通”Javascript Object 来存储快照。 The following code solved my problem:
以下代码解决了我的问题:
db.collection("Users").get().then(function(querySnapshot){
querySnapshot.forEach((doc) => {
db.collection("Users").doc(doc.id).get().then(function(snapshot){
var user = snapshot.data();
var registrationToken = user.token;
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.