I had a working firebase realtime database function that i wrote previously, however as i changed my database from realtime database to firestore it isnt working right now, i converted a bit but i am having problem to figure out how to convert (.then ....) part. What i would like to do is when a users status field changes in its document i want the function to query in the firestore database and look for other ppl's documents whose status field are also waiting and pick one of them randomly, then change its document values as below in the example
Here is a part of the original firebase realtime database function, it is
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sayi = functions.database.ref("/users/{uid}/status").onWrite((change, context) => {
console.log("status degisti");
var rastgele = Math.floor(Math.random() * 2);
var status = change.after.val();
var user = change.after.ref.parent.key;
if (status ==="waiting") {
const events = admin.database().ref('users');
const query =events.orderByChild('status').equalTo('waiting').limitToFirst(2);
query.on("value",
function(data) {
var waitinggameusers = data.val();
var keys = Object.keys(waitinggameusers);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if(key!==user){
var updates = {};
updates["/users/"+user+"/rakip"] = key;
updates["/users/"+key+"/rakip"] = user;
updates["/users/"+user+"/rakipsallama"] = "";
updates["/users/"+key+"/rakipsallama"] = "";
updates["/users/"+user+"/status"] = "on";
updates["/users/"+key+"/status"] = "on";
updates["/users/"+user+"/turn"] = "off1";
updates["/users/"+key+"/turn"] = "off2";
admin.database().ref().update(updates);
return true;
}
}
}, sorunlu);
}
});
my current firestore version:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.yenisayi3 = functions.firestore.document('users/{userId}').onUpdate((change, context) => {
const newValue = change.after.data();
const previousValue = change.before.data();
const userdoc = context.params.userId;
if (newValue.status ==previousValue.status) {
console.log("status degismedi");
return true;
}else{
console.log("status degisti");
var status = newValue.status;
if(status==="off"||status==="on"||status==="win"){
return false;
}
if (status ==="waiting") {
return db.collection('users').where('status', '==', 'waiting').get().then(
result=>{
if (result.docs.length === 0) {
return false;
}else{
return result.doc[0].ref.update({
status: 'on',
});
}
});
}
}
});
Currently i am getting
TypeError: Cannot read property '0' of undefined
at db.collection.where.get.then.result (/srv/index.js:31:24)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
My database layout is like this: