Update data if exist in firebase - firebase

I'm trying to update a data if it exists
var ref = firebase.database().ref().child('users');
var refUserId = firebase.database().ref().child('users').orderByChild('id').equalTo(Auth.$getAuth().uid);
refUserId.once('value', function (snapshot) {
console.log(snapshot);
if (snapshot.exists()) {
snapshot.ref().update(vm.user_infos);
} else {
ref.push({
player: vm.user_infos.player,
id: vm.user_infos.id
}, function(error) {
console.log(error);
})
}
});
Push is working fine, but the update did not.
snapshot.ref is not a function
In the snapshot () log console:
I tried this way too:
if (snapshot.exists()) {
refUserId.update({
player: vm.user_infos.player,
id: vm.user_infos.id
}, function(error) {
console.log(error);
})
Result:
refUserId.update is not a function
User structure

The first problem is that the snapshot's ref property is an object - not a function.
The second is that the snapshot refers to the users path, so you should check for a user that matches your query like this:
var ref = firebase.database().ref().child('users');
var refUserId = ref.orderByChild('id').equalTo(Auth.$getAuth().uid);
refUserId.once('value', function (snapshot) {
if (snapshot.hasChildren()) {
snapshot.forEach(function (child) {
child.ref.update(vm.user_infos);
});
} else {
snapshot.ref.push({
player: vm.user_infos.player,
id: vm.user_infos.id
});
}
});
And if you want to know when the update or push has completed, you could use promises:
refUserId
.once('value')
.then(function (snapshot) {
if (snapshot.hasChildren()) {
return snapshot.forEach(function (child) {
child.ref.update(vm.user_infos);
});
} else {
return snapshot.ref.push({
player: vm.user_infos.player,
id: vm.user_infos.id
});
}
})
.then(function () {
console.log('update/push done');
})
.catch(function (error) {
console.log(error);
});

Related

Retrieve data from the firebase dynamic link

Im trying to get the data from the generated firebase dynamic link.
I passed Id while generating the dynamic link. I need to get the particular id from the generated dynamic link. Can you please help me.
Where it generates link as :https://thejyotistore.page.link/jNngseAasXzE5SuSA
const ShareLink = ({
fallbackUrl, id, product }) =>
{
const buildLink = async () =>
{
let link = await axios({
method: "POST",
url:
`https://firebasedynamiclinks
.googleapis.com/v1/shortLinks?
key=AIzaSyDNZvtkjAqf8c9esg
gSEzV2 L7. 3vEUv1FfQ`,
headers: {
"Content-Type":
"application/json",
},
data: {
dynamicLinkInfo: {
domainUriPrefix: `https://thejyotistore.page.link`,
link: `https://youtube.com/${id}`,
androidInfo: {
androidPackageName: "com.jyotistore.main",
},
},
},
});
if (link.status === 200 && link.data.hasOwnProperty("shortLink")) {
console.log(link.data.shortLink);
return link.data.shortLink;
}
};
const shareLink = async () =>
{
let shareUrl;
try {
shareUrl = await buildLink();
console.log(shareUrl);
} catch (error) {
console.log(error);
}
try {
if (shareUrl !== "") {
const result = await Share.share({
message: `Hey, ${"\n \n"}I would like to invite you to check out this New App from Jyoti Store. ${"\n \n"} ${product}Download the App now: ${"\n \n"} ${shareUrl}`,
});
}
} catch (error) {
console.log(error);
}
};

Firebase Cloud Function I want to change all user data

exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 20 * * *')
.timeZone('Asia/Seoul') // Users can choose timezone - default is America/Los_Angeles
.onRun((context) =>
{
var allUsers = [];
return admin.auth().listUsers()
.then(function (listUsersResult)
{
listUsersResult.users.forEach(function (userRecord)
{
// For each user
var userData = userRecord.toJSON();
allUsers.push(userData.uid);
console.log(allUsers);
});
//res.status(200).send(JSON.stringify(allUsers));
}).then(function ()
{
allUsers.forEach(function (elem)
{
db.ref(`Data/${elem}/Enter`).update({ test: 0, test2: 0 });
});
})
.catch(function (error)
{
console.log("Error listing users:", error);
//res.status(500).send(error);
});
});
By getting the UIDs of all users at a specific time
I want to change the data with UID as parent But An error has occurred
Each then() should return a value or throw promise/always-
Could you please let me know what's wrong with my code?
Maybe try adding a return statement to each then block like so:
return admin.auth().listUsers()
.then(function (listUsersResult)
{
listUsersResult.users.forEach(function (userRecord)
{
// For each user
var userData = userRecord.toJSON();
allUsers.push(userData.uid);
console.log(allUsers);
});
return true; //<--------------- add this return statement
}).then(function ()
{
allUsers.forEach(function (elem)
{
db.ref(`Data/${elem}/Enter`).update({ test: 0, test2: 0 });
});
return true; //<--------------- add this return statement
})
.catch(function (error)
{
console.log("Error listing users:", error);
//res.status(500).send(error);
});

Async / Await Vuex

I want to call an action in created hook, wait until is done and in same hook to display the result. Is that possible?
I tried to put async / await in actions but doesn't help.
This is the action property with the async function in the store:
actions: {
async FETCH_USER({commit}) {
await firebase.firestore().collection('test').get().then(res => {
commit('FETCH_USER', res.docs[0].data())
})
}
}
created() {
this.FETCH_USER()
console.log(this.GET_USER)
},
methods: {
...mapActions([
'FETCH_USER'
]),
login() {
if(this.$refs.form.validate()) {
console.log('welcome')
}
}
},
computed: {
...mapGetters([
'GET_USER'
])
}
export default new Vuex.Store({
state: {
user: null
},
getters: {
GET_USER: state => state.user
},
mutations: {
FETCH_USER(state, user) {
state.user = user
}
},
actions: {
FETCH_USER({commit}) {
firebase.firestore().collection('test').get().then(res => {
commit('FETCH_USER', res.docs[0].data())
})
}
}
})
async/await version
async FETCH_USER({ commit }) {
const res = await firebase.firestore().collection('test').get()
const user = res.docs[0].data()
commit('FETCH_USER', user)
return user
}
async created() {
// The action returns the user out of convenience
const user = await this.FETCH_USER()
console.log(user)
// -- or --
// Access the user through the getter
await this.FETCH_USER()
console.log(this.GET_USER)
}
You need to await the action call because it is an async function.
Promise version
FETCH_USER({ commit }) {
return firebase.firestore().collection('test').get().then(res => {
const user = res.docs[0].data()
commit('FETCH_USER', user)
return user
})
}
created() {
this.FETCH_USER().then(user => {
console.log(user)
})
// -- or --
this.FETCH_USER().then(() => {
console.log(this.GET_USER)
})
}

How can I update a document found in a query?

I want to update document found by a query. Actually I'm trying the following approach:
export const add_user = functions.https.onRequest((request, response) => {
corsHandler(request, response, () => {
const collectionReference = db.collection("users");
const query = collectionReference.where("name", "==", "John");
fbid_query.get()
.then(function(querySnapshot) {
if (querySnapshot.empty) {
console.log("John notfound");
} else {
console.log("John found!");
querySnapshot.forEach(function (documentSnapshot) {
add_update(query, "George");
});
}
response.json([]);
})
.catch(function(error) {
response.json([]);
});
});
});
.
const add_update = function (query, new_name) {
query.get(function(querySnapshot) {
querySnapshot.forEach(function(document) {
console.log("entered in forEach");
document.ref.update({
name: new_name
});
});
}).then(function () {
console.log("success");
})
.catch(function(error) {
console.error("error: ", error);
});
}
The only console.log that appears is success, although nothing is updated and John indeed exists in Cloud Firestore.
What am I doing wrong?
PS: I don't know if it matters but before I actually try to update, I call query.get() just to check if something exists (and after I call that approach to update).

Unable to upload image from RN app to meteor backend

I want to upload image from my RN app to meteor backend. I am using "react-native-image-picker": "^0.26.7" for getting imagefile from gallery or camera and uploading to meteor using package react-native-meteor to collectionFs this is my code of RN app where I am calling meteor method for image upload as soon as user select image:
_handleSelectFile() {
const { order } = this.state;
var options = {
title: 'Select Avatar',
storageOptions: {
skipBackup: true,
path: 'images'
}
};
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else {
// let source = { uri: response.uri };
// You can also display the image using data:
let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
order: {
...order,
fileName: response.fileName
}
});
let fileData = response.data;
// const body = new FormData();
// body.append('file',fileData);
var photo = {
url: fileData,
type: 'image/jpeg',
name: 'photo.jpg',
};
Meteor.FSCollection('orderImages').insert(photo, function (err, res) {
if (err) {
console.log('error during uploading');
} else {
console.log('uploading successfully');
// _this.props.navigator.pop();
}
});
}
});
}
and this is my server side code:
export const Orders = new Mongo.Collection('orders');
export const OrderImages = new FS.Collection("orderImages", {
filter: {
maxSize: 1048576,
allow: {
contentTypes: ['image/*'],
}
},
stores: [new FS.Store.FileSystem("orderImages")]
});
if (Meteor.isServer) {
OrderImages.allow({
insert: function () {
return true;
}
});
}
and I am getting error like this:
ExceptionsManager.js:65
Cannot read property 'apply' of undefined

Resources