node.js - 使用 Firebase Admin SDK (NodeJS) 将数据导入 Firestore 不适用于所有集合
问题描述
我正在使用 Firestore 作为我的 React 网络应用程序的数据库。在使用 cypress 运行浏览器测试之前,我执行了一个 NodeJS 脚本,该脚本会导入这些测试所需的数据。我的 Firebase 计划设置为 Blaze(即用即付),因为免费版本不支持导入。
我有 3 个导入数据的集合 - 组织、配置文件、产品。使用相同的代码,导入适用于组织和配置文件,但不适用于产品:
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: `https://<myFirebaseProjectId>.firebaseio.com`
});
const testOrg = {
name: "testOrgName",
createdAt: Date()
};
//add organization
admin.firestore().collection("organizations").add(testOrg)
.then(createdTestOrg => {
//works fine with organizations
console.log("Successfully created new org:", createdTestOrg.id);
const testProfile = {
name: "testProfile",
organization: admin.firestore().doc(`organizations/${createdTestOrg.id}`)
createdAt: Date()
};
//add profiles
admin.firestore().collection("profiles").add(testprofile)
.then(createdTestProfile => {
//works fine with profile
console.log("Successfully created new profile:", createdTestProfile .id);
let productItem = {
isDeleted: false,
createdBy: admin.firestore().doc('profiles/' + selectedUser[0].uid),
createdAt: Date()
};
productItem.name = makeRandomName(10)
//add product
admin.firestore().collection("products").add(productItem)
.then((newProd)=>{
// I never get here
console.log("Successfully created test product");
})
.catch(error => {
// I never get here either
// eslint-disable-next-line no-console
console.log("Error creating test product:", error);
process.exit(1);
});
});
});
这是带有完整代码的要点:https ://gist.github.com/DurkoMatko/1097d1c18a00d5fd4195253205c53ff2
如果新文档尚不存在,我也尝试替换collection("products").add(product)
为应该创建新文档。collection("products").doc(product.id).set(product)
仍然没有成功。此外,既不在.then
也不在断点。catch
部分触发。这些行只是默默地发生,但没有创建新的产品文档。
请问有人知道吗?
解决方案
好的,我通过将产品直接创建为.add
函数的参数而不是将其存储为const
变量,然后将其传递给.add
. 我不知道为什么会这样,而且我在问题中发布的代码也不起作用。希望它对将来的人有所帮助。
admin
.firestore()
.collection("products")
.add({
name: "BrowserTestProduct26",
createdAt: Date.now(),
createdBy: admin.firestore().doc(`profiles/${userRecord.uid}`),
isDeleted: false,
category: categories[Math.floor(Math.random() * categories.length)]
})
.then(createdProduct => {
console.log("Successfully created new product:", createdProduct.id);
})
.catch(error => {
console.log("Error creating test product:", error);
process.exit(1);
});
推荐阅读
- python - 正则表达式python中的表达式
- api - URL 参数作为 null 传递,而不是预期传递的参数
- java - 在 android studio 中安装 genymotion 时遇到问题
- python - 将 europarl 模块/数据集导入 python 的问题
- javascript - jQuery确定音频是否播放完毕并在此之后触发功能
- kubernetes - 使用 Traefik 和 DigitalOcean 为 Kubernetes Pod 获取真实 IP
- python - 请解释 `scrapy crawl` 命令的第一个参数
- html - 链接采用不同链接的样式
- c++ - 类模板的成员函数的变量无参数
- c - 调用特定函数后,while循环执行了两次