Javascript Firestore特定数据读取不适用于变量,但适用于静态值
我正在尝试从firestore数据库查询特定文档。问题似乎是,如果我静态地添加Javascript Firestore特定数据读取不适用于变量,但适用于静态值,javascript,firebase,vue.js,google-cloud-firestore,vuex,Javascript,Firebase,Vue.js,Google Cloud Firestore,Vuex,我正在尝试从firestore数据库查询特定文档。问题似乎是,如果我静态地添加doc(id),它可以工作,但对于变量,它甚至不能工作,因为变量具有与我静态测试的值完全相同的正确值 我试图检索的文档是/users集合下的用户节点/文档 read是我用来检索数据的函数: export default class GenericDB { constructor(collectionPath) { this.collectionPath = collectionPath }
doc(id)
,它可以工作,但对于变量,它甚至不能工作,因为变量具有与我静态测试的值完全相同的正确值
我试图检索的文档是/users
集合下的用户
节点/文档
read
是我用来检索数据的函数:
export default class GenericDB {
constructor(collectionPath) {
this.collectionPath = collectionPath
}
/**
* Read a document in the collection
* @param id
*/
async read(id) {
const result = await (await firestore())
.collection(this.collectionPath)
.doc(id)
.get()
const data = result.exists ? result.data() : null
if (isNil(data)) return null
this.convertObjectTimestampPropertiesToDate(data)
return { id, ...data }
}
}
这是我的vuex操作:
getUser: ({ commit }, userId) => {
return new Promise((resolve, reject) => {
//usin UsersDB() instead of Generic() because my UsersDB() has constructor with correct path to /users
new UsersDB().read(userId).then(user => {
//Empty user if userId value is from variable and not empty if I use static value
resolve(user)
})
})
}
我确实这样说:
mounted() {
if (this.id) {
//getUser function is declared inside ...mapActions('authentication', ['getUser'])
this.getUser(this.id)
}
}
更新1:我用逻辑运算符将静态字符串与变量进行了比较,结果发现变量userId
的末尾有空格。我不知道它为什么会来,从哪里来
没有错误,只有空数据。我看不出这个简单的查询有什么错。感谢您的帮助 尝试以这种方式建立连接,而不是直接使用它
const db = firebase.firestore();
async function read(id) {
const result = await db
.collection(this.collectionPath)
.doc(id)
.get()
const data = result.exists ? result.data() : null
if (isNil(data)) return null
this.convertObjectTimestampPropertiesToDate(data)
return { id, ...data }
}
通常,我们用于获取文档的标准格式是:
const db = firebase.firestore();
const result = await db
.collection("collection_name")
.doc("document_id")
.get();
我希望这对你有帮助。请让我知道任何问题
编辑完问题后,我尝试传递一个有效变量,我得到了回答。这是给我的文件数据
//Firebase
const admin = require("firebase-admin");
let serviceAccount = require("./firebase.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
let db = admin.firestore();
//End of Firebase
id = "lWxkvqZnBxNRke4SFyJj"
async function getData(id) {
const result = await db
.collection("users")
.doc(id)
.get();
data = result.data()
console.log(data)
return data
}
getData(id)
如果我将userId与逻辑运算符进行比较,结果发现它们并不完全相同。变量版本的末尾有空格
因此,解决方案是使用
userId.replace(/\s/g),)
我最近也面临同样的问题。然后我发现我的字符串有引号。下面的代码解决了这个问题
roomId.trim().replace(/['"]+/g, '')
很抱歉,除了函数声明语法和初始化
firestore()
的方式之外,您的答案似乎没有什么不同,但嵌套的wait调用可能没有正确解析promise。试一试我初始化firestore的方式可以提高性能,而且没有任何问题,因为正如我所说的,它在查询中使用静态值提供值。Firebase id是自动生成的,或者您正在定义?@aryansingh我使用自动生成的UID作为id。