I'm using Parse to handle my backend and I'm encountering issues grabbing data from my Parse objects. I've seen many questions similar to this, but none with a straightforward answer.
My User objects have a field called groupsArray which is an array that contains Group objects. Each Group object then contains a field called groupName, which is simply the name of that particular group object.
Here is my trouble. I'm grabbing the current user via
var user = Parse.User.current();
then I grab the groupsArray and the groupNames via
var groupsArray = user.get("groupsArray");
var groupName = groupsArray[i].get("groupName");
Initially this works after I add a group, however, my problem comes after I refresh my browser. After refreshing my browser, all my groupName fields are undefined. When I try and grab their id, it works, but all the personal fields that I created for that object is undefined. When I go to my applications dashboard on parse.com, I see all the objects with their groupNames. Anyone know what's going on?
More detailed code:
Inside groups.js, which calls modelGroups.js:
$('#tester').on('click', function() {
populateSidebar();
});
Inside modelGroups.js:
function populateSidebar(){
var groupsArray = Parse.User.current().get("groupsArray");
for (var i=0; i<groupsArray.length; i++) {
var groupName = groupsArray[i].get("groupName");
console.log(groupName); // ALL of these are undefined after a browser refresh
}
}
And yes, even after refreshing the browser, Parse.User.current() is fetching the correct user, user.id, and username
It seems that the group data needs to be fetched from database again after refresh to me. Never happened on iOS since I enabled local datastore for me.
Related
To summarize, I am working with 2 collections - 'usercollection' and 'groupcollection' and I would like to associate users with groups. I don't want to have 2 copies of all the user documents so I have a unique ID attribute for each user that I want to use to associate specific users with specific groups. This is all running on a localhost webserver so I'm getting the input from an html page with a form in it where you enter 'username' and 'groupname'. I tried using the .distinct() function with query as 'username' and the target field/attribute as 'uid'.
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
// Set query and options for searching usercollection
var query = {"username" : userName};
const fieldName = "uid";
// Set our collections
var users = db.get('usercollection');
// Get UID corresponding to username
var uidToAdd = users.distinct(fieldName, query);
This is what I attempted (with some other lines that aren't relevant taken out) but it just returned a null object so I'm at a bit of a loss. Also, I'm still a beginner with nodejs/javascript/mongoDB so the more informative the answer the better! When I do the same code in the mongo shell I can get the actual value of the 'uid' attribute so I really don't know what's going wrong
I am not sure I am following you. But if I understood correctly, if you want to make a relationship between 'usercollection' and 'groupcolletion', you can simply create those 2 collections and each user in 'usercollection' should have a field with 'groupid' as a reference. In this way, you can access 'groupcollection' easily.
Here is an example with using mongoose.
In User model
...
groupId: {
type: mongoose.Schema.Types.ObjectID
ref: "Group"
}
...
Later you can also use 'populate' to fetch 'Group' information.
...
let data = await User.findById(id).populate('groupId');
...
I am developing a web app for work that adds an editor to a spreadsheet and then removes that editor when his/her step is complete.
I am running into an issue where I can't remove the editor via the User object. The User object returned by .getActiveUser() isn't found in the User[] array returned by .getEditors().
Example:
var editors = SpreadsheetApp.getActive().getEditors() //returns User[]
var user = Session.getActiveUser(); //returns User
return editors.indexOf(user) // returns -1
This happens even though the active user is an editor of the spreadsheet in question.
I can get around this issue by removing the user via email address (i.e. removeEditor(email)), but this seems like an extra step.
Does anyone know why these two User objects wouldn't be the same? Is this a bug?
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());
});
});
I'm using Lawnchair, and I've managed to store a value locally. Something like this:
var Users = new Lawnchair({table:'Users', adaptor:'dom'});
function save_prompt()
{
var UserName = prompt("Your Username","John Doe");
if (UserName!=null && UserName!="")
{
Users.save
({key:'UserData', SavedUserName:UserName});
}
}
function recall_prompt()
{
Users.get
('UserData',function(r)
{
document.getElementById('Message').innerHTML = r.SavedUserName;
}
);
}
I call both functions save_prompt & recall_prompt using buttons binded with onclick.
Basically this script will pop up a textfield to enter your username (John Doe is default) and saves it.
With recall_prompt, it worked fine by showing the saved username in the html div id="Message".
My question is, how to save a second, third, and beyond usernames? And how to retrieve them all to show in the html div? I've tried numerous methods that can be found on the 'net but I just can't get it to work. It seems the new username always overwrites the old ones.
Lawnchair saves data as Key:value pairs. So if u save another username with the same key, (UserData), it'll always get overridden. To save more usernames u'll have to change the keys. Make it UserData_1, UserData_2, like that.
Or you could store an array of usernames with the key 'UserData', so each time u need to save a username, get the array from DB, then add the new username to it and resave it.
I have code that, when a user is logged in, selects recipes that apply to him based on the ingredients (items) he has previously identified identified as possessions.
This code gets the id's of the items the user already has:
if request.user.is_authenticated():
user_items = [possession.item for possession in request.user.possession_set.all()]
user_items_ids = [item.id for item in user_items]
uids = set(user_items_ids)
The following code, which already existed, is where I run into problems...
recipes = [(recipe, len(set([item.id for item in recipe.items.all()]) & uids), recipe.votes) for recipe in recipes]
I created another part of the site that allows people who have not yet signed up to just pick a few ingredients. I do this with some jQuery on the front end, then send the results to the backend:
var ingredient_set = [];
$('.temp_ingredient').each(function(index){
ingredient_set[index] = $(this).attr('id').substr(4);
});
$.get('/recipes/discover', { 'ingredients': ingredient_set },
function(){
alert("Success");
});
The problem is when I receive them on the Django side, with this code:
uids = request.GET['ingredients']
I get the following error:
unsupported operand type(s) for &: 'set' and 'unicode'
Basically, I know they aren't in the same format, but I don't know how to get them to be compatible.
You are sending a JavaScript array in the query string of your GET request. Therefore you should use request.GET.getlist. Just using request.GET[key] gives you the last value for that key.
>> request.GET['foo[]']
u'5'
>> request.GET.getlist('foo[]')
[u'1', u'2', u'4', u'5']
Note that the values are unicode, but you probably need them as integers, so be sure to convert them.
uids = request.GET.getlist('foo[]')
uids = set([int(x) for x in uids])
I'm not sure why my key is actually foo[] and not just foo, but as you get no KeyError, request.GET.getlist('ingredients') should work.