Parse.com and JavaScript SDK.
I have a class called "FriendRequest" which I want to create a relationship with a child class called "myBadges"
The myBadges class stores multiple uploads by different users and I want to link it back to the FriendRequest class so that when I user uploads something, all of these can be accessed via the FriendRequest class using a field name "Item".
At the moment the code looks like this, which is saving the users upload to the "myBadges" class. But how do I add the relationship?
Do I just add this under the success function?
I have created the relationship column "BADGE" in the data browser already
var relation = user.relation("FriendRequest");
relation.add(BADGE);
EXISTING CODE
Parse.initialize("xxxxxxxxx", "xxxxxxxxxxx");
var MyBadges = Parse.Object.extend("myBadges");
var userbadges = new MyBadges();
var user = Parse.User.current();
$(document).ready(function () {
$("#send").click(function () {
var badgeselected = $('#badgeselect .go').attr("src");
userbadges.set("BadgeName", badgeselected);
userbadges.set("fromUser", user);
userbadges.set("BadgeStatus", "BadgeConnected");
userbadges.save(null, {
success: function (results) {
// The object was saved successfully.
console.log(user);
//location.reload();
},
![enter image description here][1]
![enter image description here][3]
you could try reading the Rest API on 'roles' & 'creating roles'
it explains how to add a relation , ie an array of children objs from a diff class
youre using JS so here is some code that also adds an array of children (type=_User):
success: function(parent) {
_role = parent;
qu.get(userId, {
success: function(child) {
//setters on _role
_role.getChildren().add(user);
_role.save();
response.success(_role.toJSON());
},
error: function(object, error) {
console.log('got role, failed on get user');
}
});
}
Related
I have the following db structure in firebase
I'm trying to grab data that belongs to a specific user id (uid). The documentation has the following example:
firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});
But how can I retrieve data from my example without knowing the unique key for each object?
Update:
I tried a new approach by adding the user id as the main key and each child object has it's own unique id.
Now the challenge is how to get the value of "title".
firebase.database().ref('/tasks/').orderByChild('uid').equalTo(userUID)
Well that is pretty straightforward. Then you can use it like this:
return firebase.database().ref('/tasks/').orderByChild('uid').equalTo(userUID).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});
Of course you need to set userUID.
It is query with some filtering. More on Retrieve Data - Firebase doc
Edit: Solution for new challenge is:
var ref = firebase.database().ref('/tasks/' + userUID);
//I am doing a child based listener, but you can use .once('value')...
ref.on('child_added', function(data) {
//data.key will be like -KPmraap79lz41FpWqLI
addNewTaskView(data.key, data.val().title);
});
ref.on('child_changed', function(data) {
updateTaskView(data.key, data.val().title);
});
ref.on('child_removed', function(data) {
removeTaskView(data.key, data.val().title);
});
Note that this is just an example.
On our website I want people to be able to report if a video is uploaded on Youtube so we have 3 fields on our website. A Username, password and video Id field. When the user clicks the Html button we have it call a javascript function.
function reportUpload() {
Parse.Cloud.run('report_upload',
{
username: "testUser",
password: "testPassword",
videoId: "VQv9xfOfLOY"
},{
success: function(result) {
//Do Neat Stuff
},
error: function(e) {
//error
}
});
}
That then calls our cloud code function. We need the cloud code function to pull the usernames from the User class and test if any of them match. If any do match they will then need to check if the passwords match. if all of that doesn't fail it will send a push notification to one of the users of the app.
So far in the cloud code funtion I have figured out how to query all the usernames.
Parse.Cloud.define("report_upload", function(request, response) {
console.log(request.params);
var query = new Parse.Query(Parse.User);
query.find({
success: function(results){
var users = [];
//extract out user names from results
for(var i = 0; i < results.length; ++i){
users.push(results[i].get("username"));
}
response.success(users);
console.log(JSON.stringify(users));
}, error: function(error){
response.error("Error");
}
});
});
Thanks
Seems like you want to check if a particular user has made an account already with a particular username.
You will have to query the User class. The user class is secured by default.
In the cloud code, you should write Parse.useMasterKey(); to have a full access (Careful, read note below).
var myquery = new Parse.Query(Parse.User);
myquery.equalTo("username",yourUsernameHere);
myquery.find({
success: function(results){
if(results.length === 0)
{
// User not found
}
else
{
// found
}
});
Note: Using the master key overrides all individual access privileges for your data. Be absolutely sure what you are doing.
I am quite new to Parse.
I have a database set up using this code:
var Class = Parse.Object.extend("Class");
var Team = Parse.Object.extend("Team");
var Student = Parse.Object.extend("Student");
var newClass = new Class();
newClass.set("name", className);
newClass.set("code", classCode);
newClass.set("creator", currentUser);
var classACL = new Parse.ACL(currentUser);
classACL.setPublicReadAccess(true);
newClass.setACL(classACL);
newClass.save();
for (var i = 0; i < teamNames.length; i++) {
var team = new Team();
team.set("name", teamNames[i]);
var teamACL = new Parse.ACL(currentUser);
teamACL.setPublicReadAccess(true);
team.setACL(teamACL);
team.save();
for (var j = 0; j < studentNames[i].length; j++) {
if (studentNames[i][j]) {
var student = new Student();
student.set("name", studentNames[i][j]);
student.set("parent", team);
student.save();
}
}
team.set("parent", newClass);
team.save();
}
newClass.save(null, {
success: function(newClass) {
//success
},
error: function(newClass, error) {
//fail
}
});
Here Class, Team, and Student are modeled as one-to-many relationships.
Now when a student signs up for the class using his or her own user account, the corresponding Student's user column is set to the current user.
Then I want to list all the classes whose creator OR one of its student's user column (if exists) equals to currentUser.
How do I create such a query referencing multiple classes in Parse (or how can I optimize the database so that such a query can be made as efficient as possible -- without having to create two separate queries?)
Any help is appreciated.
Clarification:
I knew that I could do an or query as described in Parse docs (I should have stated this in the question), however, my question is about doing so on relational data (defined by a pointer type property to parent). Here I need user be a property of a Student instance, which belongs to Team, and then to Class, and I'd like to filter only Class objects that has either its creator property or one of its grandchildren's (an instance of Student) user property equal to the currentUser, effectively listing only the classes that you created or are registered as a student.
Since the current database schema is having nested Pointers, there is no easy way to achieve this without adjusting it.
Database Schema
In Class class, add a Relation or Array field to contain references to Student/User objects. If you use User as object pointer, we wouldn't need to look up for Student at first.
Query
I assume that you have students as new Array field in Class class. students contains User objects.
var user = Parse.User.current();
var studentQuery = new Parse.Query(Class);
var creatorQuery = new Parse.Query(Class);
studentQuery.equalTo("students", user);
creatorQuery.equalTo("creator", user);
var query = Parse.Query.or(studentQuery, creatorQuery);
query.find().then(function(objects){
// Proceed with the results
},function(error){
// Handle error
});
Ok, what you want to do in an OR query with an internal subquery. One call to parse and you can filter the student properties using the subquery.
var studentQuery = new Parse.Query(Student);
studentQuery.equalTo("user", Parse.User.current());
var firstQuery = new Parse.Query(Class);
firstQuery.matchesQuery("student", studentQuery);
var secondQuery = new Parse.Query(Class);
secondQuery.equalTo("creator", Parse.User.current());
var mainQuery = Parse.Query.or(firstQuery, secondQuery);
mainQuery.find({
success: function(results) {
// results contains a list of Classes where the user is either the creator or the user property of the student (if available)
},
error: function(error) {
// There was an error.
}
});
In my cloud code I want to retrieve the first object in the "Messages" class. Then i want to grab some information from that object, send it to another class, and finally delete that object from the "Messages" class i originally pulled it from. Below is my code, however it doesn't work. How should i rework this?
Should i use a different approach than the "destroy" method such as collection.remove?
Parse.Cloud.afterSave("sendMessage", function(Parse.Message, response) {
var body = null;
var senderName = null;
var senderId = null;
var randUsers = [];
var query = new.Parse.Query(Parse.Message);
query.find({
success: function(results){
body.push(results[1].get("messageBody"));
senderName.push(results[1].get("senderName"));
senderId.push(results[1].get("senderId"));
results[1].destroy({
success: function(results[1]){
//the first object in the class "Messages" was deleted
}, error: function(results[1], error){
//the first object was not deleted
}
});
response.success(getUsers);
}, error: funtion(error){
response.error("Error");
}
});
});
to avoid confusion: "getUsers" is an arbitrary function call.
Duplicate question with the entry;
Query entire class vs first object in the class
However, if you want to delete a specific object you need something which uniquely identify the
object. Then, one way is using the Parse object id to delete the object from class.
To delete the object via cloud, you need to use the destroy method of ParseObject. But if you have multiple objects then you can use destroyAll method. One example of ParseObject delete method on javascript API is below;
var yourClass = Parse.Object.extend("YourClass");
var query = new Parse.Query(yourClass);
query.get("yourObjectId", {
success: function(yourObj) {
// The object was retrieved successfully.
yourObj.destroy({});
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
}
});
Hope this helps,
Regards.
Some changes into above :
var missingDataQuery = new Parse.Query(missingDataObj)
missingDataQuery.equalTo('projectId',project);
var getMissingData = missingDataQuery.find({
success: function(yourObj) {
console.log('here')
yourObj[0].destroy({})
},
error: function(object, error) {
}
});
Here we getting object and then destroying it.
func deleteImage(imageId: String) {
let query = PFQuery(className: "ClassName")
query.whereKey("imageId", equalTo: "\(imageId)")
query.findObjectsInBackground {
(objects:[PFObject]?, error: Error?) -> Void in
if error == nil && (objects != nil) {
for object in objects! {
object.deleteInBackground()
print("object deleted")
}
}
}
}
I've just started developing with Windows Azure. So far so good but I'm stuck with a very basic question: How to insert an item into a different table from a mobile services script? The code I have found on Windows Azure blogs doesn't seem to work as advertised:
function insert(item, user, request) {
var currentTable = tables.getTable('current'); // table for this script
var otherTable = tables.getTable('other'); // another table within the same db
var test = "1234";
request.execute(); // inserts the item in currentTable
// DOESN'T WORK: returns an Internal Server Error
otherTable.insert(test, {
success: function()
{
}
});
}
Any idea of what I am doing wrong or where I could find some help on the syntax to use? Thanks!
Found the answer on another StackOverFlow Post that had never come up before, typical...
The thing I was doing wrong was not providing the name of the column to update. so instead of having:
var test = "1234";
// DOESN'T WORK because no column is declared
otherTable.insert(test, {
success: function()
{
}
});
I should have had:
var test = {code : "1234"};
// WORKS because the script knows in what column to store the data
// (here the column is called "code")
otherTable.insert(test, {
success: function()
{
}
});
So to give the entire right code:
function insert(item, user, request) {
var currentTable = tables.getTable('current'); // table for this script
var otherTable = tables.getTable('other'); // another table within the same db
var test = {code: "1234"};
request.execute(); // inserts the item in currentTable
otherTable.insert(test, {
success: function()
{
}
}); // inserts test in the code column in otherTable
}