我将Firestore用作我的React Web应用程序的数据库。在运行使用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);
});
});
});
这是带有完整代码的Gist: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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句