Reputation: 5864
I'm using Firestore as a DB for my React web-app. Before browser tests with cypress are run, I execute a NodeJS script which imports data needed for those tests. My Firebase plan is set to Blaze(pay as you go) as the free version doesn't support import.
I have 3 collections where I import the data - organizations, profiles, products. Using the same code, import works for organizations and profiles, but not products:
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);
});
});
});
Here's Gist with a full code: https://gist.github.com/DurkoMatko/1097d1c18a00d5fd4195253205c53ff2
I've also tried replacing collection("products").add(product)
with collection("products").doc(product.id).set(product)
which should create new document if it doesn't exist yet. Still no success. Also, breakpoints in neither .then
nor .catch
section trigger. Those lines just silently happen but new product document doesn't get created.
Does someone please have any idea?
Upvotes: 1
Views: 1729
Reputation: 5864
Ok, I've solved this by creating product directly as parameter of .add
function rather than storing it as const
variable before passing it to .add
. I have no idea why this works and the code I've posted in my question doesn't. Hope it helps someone in the future.
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);
});
Upvotes: 0