首页 > 解决方案 > 使用 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部分触发。这些行只是默默地发生,但没有创建新的产品文档。

请问有人知道吗?

标签: node.jsfirebasegoogle-cloud-firestorefirebase-admin

解决方案


好的,我通过将产品直接创建为.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);
      });

推荐阅读