So I've been writing some code to sync my Firestore with another program's database so I've added references.
I want my onCreate method to get a reference number from a seller entry, make a new document with that reference number as well as update orderReference field in the existing document (I want the database to handle it instead of making queries on the client/app), delete the previous order since it's ID can't be updated from functions and update the orderNumber field.
I don't get a new document created nor updated values. I'm really new to Node.js and promises. Any tips and suggestions are welcome.
exports.createOrderReference = functions.firestore.document('/orders/{order}').onCreate((snapshot, context) => {
var id = snapshot.id; //id of order document
var sellerID = snapshot.data().sellerID;
var orderNumber = 0;
var content;
var sellerSnapID;
return admin.firestore().collection('sellers').where("ID", "==", sellerID).get().then((qSnapshot) => {
var docs = qSnapshot.docs;
orderNumber = docs[0].data().orderReferenceNumber;
sellerSnapID = docs[0].id;
content = snapshot.data();
Object.assign(content, {orderReference: orderNumber});
console.log(content); // <----- last execution
return content;
}).then(() => {
return admin.firestore().collection('orders').doc(orderNumber).set(content).then(() => {
var promises = [];
promises.push(admin.firestore().collection('orders').doc(id).delete());
orderNumber++;
promises.push(admin.firestore().collection('sellers').doc(sellerSnapID).update({orderReferenceNumber: orderNumber}));
return Promise.all(promises);
});
}).catch((err) => {
return err;
});
Updated code
exports.createOrderReference = functions.firestore.document('/orders/{order}').onCreate((snapshot, context) => {
var id = snapshot.id; //id of order document
var sellerID = snapshot.data().sellerID;
var orderNumber = 0;
var content;
var sellerSnapID;
return admin.firestore().collection('sellers').where("ID", "==", sellerID).get().then((qSnapshot) => {
var docs = qSnapshot.docs;
orderNumber = docs[0].data().orderReferenceNumber;
var orderID = docs[0].data().orderReferenceNumber;
sellerSnapID = docs[0].id;
content = snapshot.data();
content.orderReference = orderNumber;
return admin.firestore().collection('orders').doc(orderID).set(content);
}).then(() => {
orderNumber++;
var promises = [];
promises.push(admin.firestore().collection('orders').doc(id).delete());
promises.push(admin.firestore().collection('sellers').doc(sellerSnapID).update({orderReferenceNumber: orderNumber}));
return Promise.all(promises);
}).catch((err) => {
return err;
});
});