Retrieve roles for user with user objectID in Cloud Code - javascript

I'm trying to retrieve roles for a desired user where I know if objectId.
exports.User.getUserRole = function(userId, success, error)
{
Parse.Cloud.useMasterKey();
console.log("getUserRole method");
var query = new Parse.Query(Parse.User);
query.
equalTo("objectId", userId)
.find({
success: function(user){
console.log("SUCCESS 1");
console.log(user);
var queryRole = new Parse.Query(Parse.Role);
queryRole
.equalTo("users", user)
.find({success: function(roles){
console.log("SUCCESS 2");
success(roles);
},
error: function(_errorRole){
console.log("FAIL 2");
console.log(_errorRole);
error(_errorRole);
}
});
},
error: function(_error){
console.log("FAIL 1");
error(_error);
}
});
But I've this strange error in the CloudCode logs:
FAIL 2 // My console.log
{"code":102,"message":"equality needs a value instead of
[map[__type:Pointer className:_User objectId:qjsmwxQ4KQ]] "}

Related

findOneAndUpdate fails using MEAN stack

Here's my code on my layout.handlebars
$(document).ready(function(){
var socket = io();
// //understand button
$(".understandbtn").click(function(){
//reset the timer every 3 second of interval
$('.actionBtnFloat').css('z-index','0');
//e_money
var deduct = 100;
var newMoney = {{user.e_money}} - deduct;
// send a message to the server that the e-money value has changed
//get the current user
socket.emit('update e-money',getUserName(), newMoney);
// console.log("Emitting the data to the server side - emoney" + getUserName() + "with the name money of :" + newMoney);
//end
clearTimeout(interval);
//send the data to the server
socket.emit('chat message', getUser());
var interval = setTimeout(function(){
$('.'+getUser()).fadeIn();
},5000);
});
socket.on('update e-money response', function (data) {
alert("Your money is: "+ data.newMoney);
console.log("Your money is:" + data.newMoney);
});
socket.on('update e-money error', function (err,data) {
if(err) throw err;
// alert("Could not update your money: "+ data.error);
// console.log("Could not update your money"+ data.error);
alert("Sucessfully updated your money");
console.log("Sucessfully updated your money");
});
And on my server here it is how i update my record but its not working
is it because of the error?
//emoney
socket.on('update e-money', function (data) {
var userName = data.username;
var newMoney = data.newMoney;
var query = {username: userName};
// update the entry on the database
User.findOneAndUpdate(query, { e_money: newMoney }, { upsert: true, new: true }, function (err, doc) {
if (err) {
io.emit('update e-money error', { error: err });
console.log(err);
} else {
io.emit('update e-money response', { e_money: newMoney });
console.log(newMoney);
}
});
});
//end emoney
Now it says couldn't update my record
Is it because im not using the _id instead?
here's my error
message: 'Cast to number failed for value "undefined" at path "e_money"',
name: 'CastError',
stringValue: '"undefined"',
kind: 'number',
value: undefined,
path: 'e_money',
reason: undefined }
By doing this achieved what i want
User.findOneAndUpdate({"username":userName},
{"$set":{"e_money": newMoney }}, { upsert: true, returnOriginal:false },
function (err, doc) {

Parse Cloud Code function get deviceToken By username

I am kinda new to the whole cloud code and I am having a bit of trouble fetching some data.
So what I basically want is a function that by giving it a 'username' that is located in the Parse.User database, it will return the user's objectId which I will then use to locate the user's session in the Parse.Session, from there I will get the installationId which I will then use in the Parse.Installation to get the device token.
Note: I have written a function that keeps only 1 session active per user.
My issue:
The Query of Parse.Session has a result which only contains 3 objects, and the installationId is not included,therefor I can not find out what is the installation id and then use it to search the Parse.Installation to get the device token.
input example:
Input:
{"from":"user1",
"msg":"hello",
"title":"Whatever title",
"to":"user2"}
Here is the existing code I currently have which doesn't work.
Parse.Cloud.define('gcm', function(request,response){
var username = request.params.to;
console.log("usr "+username);
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('username', username);
userQuery.find({
success: function(results){
var objectId = results[0].id;
console.log("obj id "+objectId);
var user = new Parse.User();
//Set your id to desired user object id
user.id = objectId;
var sessionQuery = new Parse.Query(Parse.Object.extend('Session'));
sessionQuery.include(user);
sessionQuery.find({
success: function(results1){
console.log("result classname type: "+typeof(results1[0]));
var installId = results1[0].installationId ; //here is the value which I want from the result, but the object is type of _Session which does not have installationId.
console.log("inst id "+installId);
var InstallationQuery = new Parse.Query(Parse.Installation);
InstallationQuery.equalTo('installationId',installId);
InstallationQuery.find({
success: function(results2){
var deviceToken = results2[0].get("deviceToken");
console.log("token "+deviceToken);
Parse.Cloud.httpRequest({
method: "POST",
url: " https://gcm-http.googleapis.com/gcm/send",
headers: {'Authorization' : 'key=AIzaSyDj4ISkLW7CzAQEQEhTsq3JYZK5OP8tSzY',
'Content-Type' : 'application/json'},
body: {
"data":
{
"title": request.params.title,
"msg": request.params.msg
},
"to" : deviceToken
},
success: function(httpResponse) {
response.success("Message Sent!");
console.log(httpResponse.text);
},
error: function(httpResponse) {
response.error("Error, Something went wrong.");
console.log("error 4: " + httpResponse.status);
}
});
},
error: function(error) {
//error
console.log("error 3: " + error);
}
});
},
error: function(error) {
//error
console.log("error 2: " + error);
}
});
},
error: function(error) {
//error
console.log("error 1: " + error);
}
});
});

Parse updating a set of objects

I have trouble updating a set of values in my cloud code. I have tried .save() seperately and .saveAll() but the class doesn't get updated in Parse and I get errors returned.
What I am trying to do is to get all messages from class ChatMessages which has a pointer to the Parse user and Chat class. When the method is called, the class column readAt needs to be updated to the current date. I call my method from an iOS (objective-C) app.
This is the latest version of my method:
Parse.Cloud.define("markChatAsReadForRoomAndUser", function(request, response) {
var errorMsg;
var roomName;
var _ = require('underscore.js');
var userPointer = new Parse.User.current();
if (!request.params.roomName) {
errorMsg = "Chat room needs to be identified";
} else {
roomName = request.params.roomName;
}
console.log("Checking chats for userID: " + userPointer.id);
if (!userPointer.id) {
var emptyUserMsg = "User has to be provided";
if (errorMsg) {
errorMsg = errorMsg + emptyUserMsg;
} else {
errorMsg = emptyUserMsg;
};
}
if (errorMsg) {
response.error(errorMsg);
}
var chatQuery = new Parse.Query("Chat");
chatQuery.equalTo("roomName", roomName);
chatQuery.find({
success: function(results) {
if (results.length > 0) {
var chat = results[0];
console.log("Found chat with ID: "+chat.id);
var chatMessagesQuery = new Parse.Query("ChatMessage");
chatMessagesQuery.equalTo("chat", chat);
chatMessagesQuery.notEqualTo("fromUser", userPointer);
chatMessagesQuery.equalTo("readAt", undefined);
chatMessagesQuery.find().then(function(chatMessagesQueryResults) {
_.each(chatMessagesQueryResults, function(result) {
result.set("readAt", new Date());
console.log("Setting readAt for chat message " + result.id + " which has toUser " + result.get("toUser"));
});
return Parse.Object.saveAll(chatMessagesQueryResults,{
success: function(list) {
console.log("Success updating objects");
},
error: function(error) {
console.log("Error updating objects: " + error);
},});
}).then(function(results) {
response.success(results);
console.log("Update for reatAt for chat is successfull");
}, function(error) {
response.error(error);
console.log(error);
});
} else {
response.error("No rooms found");
console.log("No rooms found");
}
},
error: function(error) {
response.error("Room name not found");
console.log(error);
}
});
});
Log output:
E2015-07-19T09:13:48.483Z]v337 Ran cloud function markChatAsReadForRoomAndUser for user CZwQL4y751 with:
Input: {"roomName":"room_czwql4y751_uoc7rjxwpo"}
Result: {"code":101,"message":"object not found for update"}
I2015-07-19T09:13:48.540Z]Checking chats for userID: CZwQL4y751
I2015-07-19T09:13:48.593Z]Found chat with ID: gfvAkirqTs
I2015-07-19T09:13:48.647Z]Setting readAt for chat message ZiWUIdUtUm which has toUser undefined
I2015-07-19T09:13:48.648Z]Setting readAt for chat message YHEBLpR04U which has toUser undefined
I2015-07-19T09:13:48.649Z]Setting readAt for chat message 0wZ4LQd8ZC which has toUser undefined
I2015-07-19T09:13:48.650Z]Setting readAt for chat message MYsYGyXI0k which has toUser undefined
I2015-07-19T09:13:48.751Z]Error updating objects: [object Object]
I2015-07-19T09:13:48.752Z]{"code":101,"message":"object not found for update"}
E2015-07-19T09:13:49.042Z]v337 Ran cloud function markChatAsReadForRoomAndUser for user CZwQL4y751 with:
Input: {"roomName":"room_czwql4y751_uoc7rjxwpo"}
Result: {"code":101,"message":"object not found for update"}
Class:
The query can be vastly simplified by making a chatMessages query relational to chats matching the user and room criteria. The code structure can be improved by not mixing callback and promise styles, and by separating logical chunks into small, promise-returning functions.
Stripping away some of the debug instrumentation you added, we get (untested, of course)...
function unreadChatMessagesInRoom(roomName, excludeUser) {
var query = new Parse.Query("ChatMessage");
query.notEqualTo("fromUser", excludeUser);
query.doesNotExist("readAt");
var chatQuery = new Parse.Query("Chat");
chatQuery.equalTo("roomName", roomName);
query.matchesQuery("chat", chatQuery);
return query.find();
}
Parse.Cloud.define("markChatAsReadForRoomAndUser", function(request, response) {
var _ = require('underscore.js');
var user = request.user;
unreadChatMessagesInRoom(request.params.roomName, user).then(function(chatMessages) {
console.log(chatMessages.length + " chat messages found");
_.each(chatMessages, function(chatMessage) {
chatMessage.set("readAt", new Date());
});
return Parse.Object.saveAll(chatMessages);
}).then(function(results) {
response.success(results);
}, function(error) {
response.error(error);
});
});

Parse Cloud Code beforeSave not running on update

I have defined a Parse Cloud Code function for beforeSave below.
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey();
var publicACL = new Parse.ACL();
publicACL.setPublicReadAccess(true);
publicACL.setPublicWriteAccess(true);
request.object.setACL(publicACL);
response.success();
});
This code runs correctly whenever I save a new Parse.User. However, when I try to update a pre-existing Parse.User, the code does not execute. Any thoughts? Below is the code I am using to update my user.
function updateStudentTypes(id, studentType, chkBox) {
var query = new Parse.Query(Parse.User);
query.get(id, {
success: function(user) {
var typeList = user.get("studentType");
if(!chkBox.checked)
typeList = removeStudentType(typeList, studentType);
else
typeList = addStudentType(typeList, studentType);
user.set("studentType", typeList);
user.save(null, {
success: function(user) {
//alert('New object created with objectId: ' + user.id);
},
error: function(user, error) {
alert('Failed to update user: ' + error.message);
}
});
},
error: function(object, error) {
alert("Error querying user: " + error);
}
});
}
Add this to the beginning of your updateStudent method:
Parse.Cloud.useMasterKey();
Edit: I thought your code was cloud code, not client side javascript.

Parse, Function only works for the current user

The following function seems to only work for my Current user, any other ObjectId that I type into the input will return a Post (Bad Request) error in the console.
var query = new Parse.Query(Parse.User);
var userInput = $('#inputObject').val();
query.equalTo("objectId", userInput);
query.first({
success: function(result) {
console.log(result.id);
result.set('money', 20);
result.save();
},
error: function(error) {
console.log("None found.");
}
});
The problem with this is that the Parse user object is only modifiable by the current user. You can get around this by creating a Cloud Code function, which modifies the money value for the intended user. Note, the cloud code function must call Parse.Cloud.useMasterKey(); Source
CloudCode Function:
Parse.Cloud.define("setMoney", function(request, response) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", request.params.userId);
query.first({
success: function (result) {
console.log(result.id);
result.set('money', 20);
result.save();
response.success();
},
error: function (error) {
console.log("None found.");
response.error(error);
}
});
});
JavaScript Call
Parse.Cloud.run("setMoney", {userId: userInput}, {
success: function(result) {
// Success
},
error: function(error) {
// Error
}
});

Categories

Resources