I am using the Firebase node.js admin sdk to create user accounts via a csv importer with custom uids. This all works fine. On succesfull creation of the account I would like to update a database reference. However whenever the function loops through to create the entries in the db it fails with the message
Uncaught Error: Firebase.child failed: First argument was an invalid path: "contractors/jk116734s". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
as you can see in the logged message above the path doesn't contain any of those unwanted characters and the path is not empty. Strangely it does update one record in the db but all the others fail. The path "contractors/jk116734s" I am also logging all the paths and none are undefined or containing invalid characters. The jk***** part of the urls are all unique fyi.
Here is my function that gets called on each succesfull account creation.
function createDbEtnryForUser(index, contractorData) {
var ni = contractorData.ni;
var path = "contractors/" + ni
console.log(path);
databaseRoot.ref(path).update(contractorData);
databaseRoot.ref(path).once('value',function(snapshot) {
$('#row-'+index).css({"background-color":"green", "color":"white"});
});
}
also you can see one entry is getting created but the rest are not.
Weirdly if I don't use the custom uid and use the auto uids created by firebase all works fine. What I don't understand though is that all the accounts do get created with the custom uid and as you can see logged I am getting the custom uid back to use in the call to update.
It looks like there may be invisible characters in the value of ni. See this answer - stackoverflow.com/a/12793237/782358 - to display those characters:
You can use encodeURI for showing the hidden stuffs.
Related
When I add $show:true to the data (shown below), the find request shows an error.
When I remove $show:true, there is no error and working fine.
Error is
Invalid query parameter $show.
I tried using different $values but the server always shows 'invalid parameter $values'
data = {$noshow:true,$show:true} ;
let res = await client.service('servv').find({query:data});
In Feathers, query parameters starting with a $ are treated as special parameters. Often they can be used to make database specific queries (instead of just querying properties) which is why they have to be explicitly allowed on the server in the service configuration (see https://docs.feathersjs.com/api/databases/common.html#options).
I'm building an Android app with React Native using Firebase to implement chat between users. I'm running tests now and found out that, on occasion, sending chat messages produces the following exception and crashes the app:
Reference.child failed: First argument was an invalid path = "undefined". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
This is the function that sends messages to the Firebase Realtime Database, triggered whenever the "send message" button is pressed:
sendMessageToFirebase(chatId, userId){
let newMessage = {created: new Date().toJSON(), text: this.state.textInput}
//getting messages data from firebase
let data = {};
console.log('REF:' + firebase.database().ref('chats'));
dataRef = firebase.database().ref('chats').child(chatId);
console.log('REF WITH CHILD: ' + dataRef);
dataRef.on('value', datasnap=>{
data = datasnap.val()
//the following function rewrites the dictionary fetched from FB to add the new message
data = this.rewriteFirebaseChatData(data, userId, newMessage);
})
//sending the data
dataRef.set(data)
this.loadMessagesFromFirebase(chatId);
}
The first console log, with just the ref, will always print, but on a seemingly random basis, the second ref will not and I'll get the exception, so I can assume that's where the issue is. Is there a way to fetch data from the child reliably?
If the error comes from the code you shared, it seems that chatId is undefined.
You'll want to check in the calling code why that happens. If this is a valid case, you'll want to check for it in sendMessageToFirebase too, for example by adding this to the start of the method:
if (!chatId) return;
I tried to create a stored procedure using the sample sp creation code from Azure docs, but i couldn't fetch the collection details. It always returns null.
Stored Procedure
// SAMPLE STORED PROCEDURE
function sample(prefix) {
var collection = getContext().getCollection();
console.log(JSON.stringify(collection));
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root r',
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var response = getContext().getResponse();
var body = { prefix: prefix, feed: feed[0] };
response.setBody(JSON.stringify(body));
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
The console shows only this.
the results shows no doc found because of not getting collection.I have passed the partition key at time of execution via explorer.
I had a similar issue. I think the Azure portal doesn't execute stored procedures properly when the partition key is not a string.
In my case I had a partitionKey that is a number. When I executed the stored procedure via the portal I always got an empty resultSet, even though I had documents in my database. When I changed the structure a little, and made my partitionKey a string, the stored procedure worked fine.
Did you create the ToDoList Database with the Items Collection? Yo can do this from the Quick start blade in the Azure portal.
And then create an SP to run against that collection. There is no partition key required, so no additional params are required (leave blank).
The Collection is created without any documents. You may choose to add documents via the Query Explorer blade or via the sample ToDoList App that is available via the Quick start blade.
You are debugging in a wrong way.
It is perfectly fine to see "{\"spatial\":{}}" in your console log, even if the collection has items. Why? well because that is a property of that object.
So regarding what you said:
the results shows no doc found because of not getting collection
is false. I have the same console log text, but I have items in my collection.
I have 2 scenarios for why your stored procedure return no items:
I had the same issue trying on azure portal UI(in browser) and for my surprise I had to insert an item without the KEY in order that my stored procedure to see it.
On code you specify the partition as a string ie. new PartitionKey("/UserId") instead of your object ie. new PartitionKey(stock.UserId)
I am having a hard time trying to push elements to a JSON file located in an external location; here's a backstory on what I am trying to achieve:
I am programming a private Discord bot and am currently working on the message-system portion of it. The whole idea is that a user's message is deleted if they aren't fully authorized onto the server; that user's message and UserID will be logged into the JSON file . The thing is, I can only log the message if a UserID is manually added to the array (using the push function, I can add the message). But, if I try to push a UserID to the file array, it acts as if the push function does not exist for this; I think the JSON is nested as well. I would appreciate any help I can get, thanks!
JSON
{"users":[{}]}
I want to put the UserID within the braces inside the brackets
Code to push to the JSON
function removeMessage(content, authorid) {
if (!messagedata.users[0][authorid]) {
messagedata.users[0].push(authorid);
}
}
Current I'm Getting:
TypeError: messagedata.users[0].push is not a function
Expected Output
{"users":[{"287423028147781654":["Hi"]}]}
The numerical value is the UserID, while 'Hi' is clearly the message
users[0] is an object, not an array (and hence has no push method). It appears you actually want to add a key to the object, so try this instead:
messagedata.users[0][authorid] = ["Hi"];
So I've been using Firebase as a database for my website (this is a web based project, using HTML, CSS and JS) and I'm running into a problem retrieving data from it.
Basically this site allows users to create a profile for a character (they can fill in the name, the characters stats etc...) and when they click submit, it'll save the values they filled out to the database.
The values are saved perfectly fine, but when I go to retrieve the data the command doesn't seem to do anything.
So in order to get the profiles, I've been trying to use this bit of code to get whatever is stored at the specified .ref(path):
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
Which according to the Firebase docs should return a list of keys at the path that I specified in .ref(). However whenever I try to access whatever is in the var, it just gives me the string that contains a link to the database that looks like this:
https://#mydatabaseurlhere.firebaseio.com/users/uid/chars
Where #mydatabaseurlhere is the url I created on the Firebase app, and the uid is the authenticated user's ID.
I've been reading the docs, and its telling me that the above code should return a list of whatever is at the path that I specified, but so far it just gives me a link. Is there something I've been missing from the Docs that'll allow me to access whatever data is currently in the database? Because I've tried to take a snapshot using .once() to no avail either. I've also set the rules on /users/ to allow anyone to read/write to the database but I'm still not able to access the data (or maybe I am accessing, I'm just missing how to retrieve it).
Either way, I'm wondering how one can go about accessing this data, as I'm extremely confused as to why I can't seem to retrieve the data that has been successfully written to the database.
You're defining a query. But that doesn't yet retrieve the data.
To retrieve the data, you need to attach a listener. For example:
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
getChar.on('value', function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key, child.val());
});
});