I have a Firebase collection of devices that have a field called state.
I want my code to loop through each document, find any one document with a state of 0, and update that state to 2. Finally, I want to grab the name of the device whose state was changed.
After running my code, it does find and update a document in the collection properly, however I am unable to return the Promise.resolve(..)
that stores the document name.
It seemingly only outputs "Transaction failure: No devices with state 0 found", meaning return Promise.reject('No devices with state 0 found');
is reached when it shouldn't be.
Here is my code:
let deviceRef = db.collection("devices");
let transaction = db.runTransaction(t => {
return t.get(deviceRef)
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=> state:', doc.data().state);
if (doc.data().state == 0) {
doc.ref.update({ state: 2 });
return Promise.resolve(doc.id + ' has been changed to state 2');
}
});
return Promise.reject('No devices with state 0 found');
});
}).then(result => {
console.log('Transaction success', result);
}).catch(err => {
console.log('Transaction failure:', err);
});
The code does reach doc.ref.update({state: 2});
because I can see the Firebase collection being properly modified, however return Promise.resolve(doc.id + ' has been changed to state 2');
does not seem to be "captured".
What am I doing wrong?
I have a suspicion that I am using promises incorrectly. Some research leads me to believe that I need to use Promise.all
or some form of map to deal with the forEach
.