react firebase firestore insert json - javascript

I am using react with firebase firestore to insert a complete collection with documents that does not already exist in firebase firestore .
With my code however no collection is inserted and I get no error as if nothing happened.
This is the code that returns my json
createJson.js
const jsonArray = [{name:"Bill" , age : "5"} ,{name:"Jom" , age : "3"} ]
return jsonArray;
insertJson.js
import 'firebase/firestore';
const db = firebase.firestore();
export const insertJson = (jsn)=>{
try{
jsn.forEach(itm=>{
let id = db.collection("doctors").doc().id;
db
.collection("doctors")
.doc(id)
.set(itm)
.then(doc=>{
console.log("Doc inserted with " +doc.id);
})
});
}catch(err){
console.log("Error : " +err);
}
}
App.js
useEffect(()=>{
const j = createJson();
insertJson(j);
},[])
So in other words no collection is created with my script with the docs inside .
I would appreciate your help .

You should use the Firestore add() method and Promise.all() as follows:
export const insertJson = (jsn) => {
try {
const promises = [];
jsn.forEach((itm) => {
promises.push(db.collection('doctors').add(itm));
});
Promise.all(promises).then((results) => {
console.log(results.length + ' doctors added');
});
} catch (err) {
console.log('Error : ' + err);
}
}
or, with map():
export const insertJson = (jsn) => {
try {
Promise.all(jsn.map((itm) => db.collection('doctors').add(itm))).then(
(results) => {
console.log(jsn.length + ' doctors added');
}
);
} catch (err) {
console.log('Error : ' + err);
}
}
If the number of doctors is less than 500 you could also use a batched write.
export const insertJson = (jsn) => {
try {
const batch = db.batch();
jsn.forEach((itm) => {
const docRef = db.collection('doctors').doc();
batch.set(docRef, itm);
});
batch.commit().then((results) => {
console.log('doctors added');
});
} catch (err) {
console.log('Error : ' + err);
}
}

Related

VueJs Failed to execute 'transaction' on 'IDBDatabase'

I want to save my posts to IndexDB and on client side to list posts even when user offline.
import { openDB } from 'idb'
const dbPromise = () => {
if (!('indexedDB' in window)) {
throw new Error('Browser does not support IndexedDB')
}
return openDB('OfflineDb', 1, upgradeDb => {
if (!upgradeDb.objectStoreNames.contains('posts')) {
upgradeDb.createObjectStore('posts')
}
})
}
const saveToStorage = async (storeName, datas) => {
try {
const db = await dbPromise()
const tx = db.transaction(storeName, 'readwrite')
const store = tx.objectStore(storeName)
store.put(datas, storeName)
return tx.complete
} catch (error) {
return error
}
}
const checkStorage = async storeName => {
try {
const db = await dbPromise()
const tx = db.transaction(storeName, 'readonly')
const store = tx.objectStore(storeName)
return store.get(storeName)
} catch (error) {
return error
}
}
export default {
checkStorage,
saveToStorage
}
Here is my service. When I try to get data;
dbService.checkStorage('posts')
I'm getting error;
DOMException: Failed to execute 'transaction' on 'IDBDatabase': One of the specified object stores was not found.
Why that's happening? I found some solutions but any of them can not solve my problem

Back4app Parse Server Retrieved ObjectId

hi i wonder why i cannot retrieve an objectId from this json object even i can printout the stringify on console.
I can retrieve all other column with no problem but not objectId. It happen to all table in my back4app Parse server.
i need the objectId in order to update certain column in my program
below is my code
1)
const parseQuery = new Parse.Query("User");
parseQuery.equalTo("username", "Azha");
let queryResult = await parseQuery
.find()
.then((results) => {
results.forEach((prod) => {
//if i change below to prod.get("objectId") error undefined appear
console.log("Product ID Available : " + prod.get("username"));
});
})
.catch((error) => {
console.log(error);
});
const parseQuery = new Parse.Query("User");
parseQuery.equalTo("username", "Azha");
try {
let todos = await parseQuery.find();
if (todos.length > 0) {
//if i change below to todos[0].get("objectId") error undefined appear
console.log("yes Approval : " + todos[0].get("companyname"));
} else {
console.log("No Approval");
}
console.log("- value is : " + JSON.stringify(todos));
console.log("----------------------");
} catch (error) {
Alert.alert("Error!", error.message);
}
below is the json printout
[{"sessionToken":"r:d9166aa9d7143463c46725d095b53946","username":"Azha","createdAt":"2021-09-21T15:27:01.088Z","updatedAt":"2021-10-10T13:01:27.126Z","companyname":"XXX","fullname":"XXX","email":"azha#abc.com.my","emailVerified":true,"accesslevel":"Maintenence","companydivision":"Maintenence","position":"Technician","phonenumber":"999","userteam":"B","useremail":"azha#abc.com.my","ACL":{"*":{"read":true},"IuBGmCtxyu":{"read":true,"write":true}},"objectId":"IuBGmCtxyu"}]
Yes i just found my solution. Using object1 below:
const parseQuery = new Parse.Query("User");
parseQuery.equalTo("username", "Azha");
try {
let todos = await parseQuery.find();
var object1 = JSON.parse(JSON.stringify(todos));
console.log("2- value is : " + object1[0].objectId);
} catch (error) {
Alert.alert("Error!", error.message);
}

How to save thousand data in Parse Platform NodeJS

I am new to the parse platform and i'm trying to insert 81000 rows of data in to the Parse DB, here the code
const uri = "/the.json"
const res = await axios.get(uri)
const dataresult = Object.keys(res.data)
if (dataresult.length > 0) {
res.data.forEach(function (datakp) {
var kp = new Parse.Object("theClass");
kp.save(datakp)
.then((res) => {
console.log('oke ' + res.id)
}),
(error) => {
console.log('err : '+ error.message)
}
})
}
There is no error in console log, and no data is saved in Parse DB, but if I only insert 1000 rows, it will save to the database.
EG:
if (dataresult.length > 0) {
res.data.forEach(function (datakp, index) {
if (index < 1000) {
var kp = new Parse.Object("theClass");
kp.save(datakp)
.then((res) => {
console.log('oke ' + res.id)
}),
(error) => {
console.log('err : '+ error.message)
}
})
}
}
Thank You
UPDATE
I fix this case based on answer #davi-macĂȘdo
here a complete code
const uri = "/the.json"
const res = await axios.get(uri)
const dataresult = Object.keys(res.data)
const objs = [];
const theKP = Parse.Object.extend("theClass")
if (dataresult.length > 0) {
res.data.forEach(function (datakp) {
var thekp = new theKP()
thekp.set(datakp)
objs.push(thekp);
})
}
Parse.Object.saveAll(objs)
.then((res) => {
console.log('oke updated ' + dataresult.length)
}),
(error) => {
console.log('err : '+ error.message)
}
The most efficient way is using Parse.Object.saveAll function. Something like this:
const uri = "/the.json"
const res = await axios.get(uri)
const dataresult = Object.keys(res.data)
const objs = [];
if (dataresult.length > 0) {
res.data.forEach(function (datakp) {
objs.push(new Parse.Object("theClass", datakp));
})
}
Parse.Object.saveAll(objs)
.then((res) => {
console.log('oke ' + res.id)
}),
(error) => {
console.log('err : '+ error.message)
}
Anyways, since you have no error and no data currently being saved, you might be kitting some memory limit. So that's something you also need to be aware about.
You're probably hitting rate limits, I can't imagine saving 81,000 records in one shot is normal behaviour for many applications.
I looked through the documentation and couldn't find anything that might mention a save limit, however sending 1000 requests would trigger most rate limit protection

How to store ID of record in Firebase cloud functions

I'm saving data in the collection in the following way:
const userEntry= {
UserId: "I want documentID here",
UserName: "",
creationDate: ""
}
const churchResult = await saveChurchData(userEntry)
const saveData = async (data: object) => {
return database.collection('users').add(data)
.then(snapshot => {
return snapshot.get().then(doc => {
doc.data()
return doc.id
}).catch(err => {
console.log('Error getting documents', err);
return null;
});
}).catch(err => {
console.log('Error getting documents', err);
return null;
});
}
Is there any way that I store "documentID" of users table in the place of UserId. How can we do that in firebase cloud functions? I'm unable to find a way to store the documentID in the documentation.
I tried following, but it is giving wrong ID not docuemntID:
const key =firebase.database().ref().push()
Since I don't see any saveChurchData() method in your code, I make the assumption that instead of doing
const churchResult = await saveChurchData(userEntry)
you wan to do
const churchResult = await saveData(userEntry)
The following would do the trick, by using the doc() method without specifying any documentPath:
const userEntry = {
UserName: "",
creationDate: ""
}
const churchResult = await saveData(userEntry)
const saveData = async (data: object) => {
try {
const docRef = database.collection('users').doc();
const docId = docRef.id;
await docRef.set({ UserId: docId, ...data });
return docId;
} catch (error) {
//...
}
}

Firebase deploy - count items in db and assign it

I'm making an iOS app and I have this problem now.
I'd like to count the number of unread messages in database and assign it in a database different closure. Like below.
exports.arrivalNotifications = functions.database.ref('/trips/{tripId}')
.onCreate((snap, context) => {
const data = snap.val();
const uid = data.uid;
var counter = 0
admin.database().ref('/messages/').on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
if (childData.read === false) {
counter += 1
}
});
})
return admin.database().ref('/users/' + uid).once('value', snapshot => {
const data = snapshot.val();
const username = data.username
var payload = {
notification: {
title: username ' has ' + counter + " unread message.",
body: 'Press for more'
}
}
admin.messaging().sendToDevice(toUser.fcmToken, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
return null;
})
.catch(function(error) {
console.log("Error sending message:", error);
});
})
})
So I want to use the counter in the payload but I can't find the way to do it. I'm not familiar with JavaScript so if someone can help me I'd appreciate.
I would write your Cloud Function as follow. Please note that I could not test it and it may need some fine-tuning/debugging... especially since it implies chaining several promises.
exports.arrivalNotifications = functions.database.ref('/trips/{tripId}').onCreate((snap, context) => {
const data = snap.val();
const uid = data.uid;
let counter = 0;
return admin.database().ref('/messages/').once('value')
.then(snapshot => {
snapshot.forEach(function (childSnapshot) {
const childData = childSnapshot.val();
if (childData.read === false) {
counter += 1;
}
});
return admin.database().ref('/users/' + uid).once('value');
})
.then(snapshot => {
const data = snapshot.val();
const username = data.username;
const payload = {
notification: {
title: username + ' has ' + counter + ' unread message.',
body: 'Press for more'
}
};
return admin.messaging().sendToDevice(toUser.fcmToken, payload);
})
.then(response => {
console.log("Successfully sent message:", response);
return null;
})
.catch(error => {
console.log("Error sending message:", error);
});
});

Categories

Resources