Cannot retrieve key values with Parse.Query - javascript

Beginner programmer here...I am trying to retrieve the value of specific key from a Parse object. I know that I am retrieving the object because certain keys return a value, i.e. createdAt returns the date value associated with it....the key I want the value for is called "task", which has a string value, but keeps returning undefined. My code looks like this:
var query = new Parse.Query("TestObject");
query.get("TC8m9X6XUB", {
success: function(object) {
console.log(object.task);
},
error: function(error) {
console.log("An error occured :(");
}
});
if I replace "object.task" with "object.createdAt" it returns a value. What am I missing here?

createdAt, objectId are reserver for Parse. So you can directly call them like object.createdAt. However, if you have a column namely task which has string value then you have to get the value via calling object.get("task"). Hope this helps.
Regards.

Use get().
In your case,
object.get('task');
Test this,
var query = new Parse.Query("TestObject");
query.get("TC8m9X6XUB", {
success: function(object) {
console.log(object.get('task'));
},
error: function(error) {
console.log("An error occured!");
}
});
In Parse, createdAt, ID and updatedAt are special fields. Hence, you can retrieve them without get().

Related

Using Lambda with Nodejs Count Some queries in Dynamo DB

After using the below to pull data from Dynamo db sucessfully
async function pullone(sessionid) {
const params = {
TableName: dynamodbTableName,
Key: {
'sessionid': sessionid
}
};
return await dynamodb.get(params).promise().then((response) => {
return response.Item
}, (error) => {
console.error('Do your custom error handling here. I am just gonna log it: ', error);
});
}
Instead of 'return response.Item' i just want to return the count instead.
I tried doing count(pullone(sessionid)) but not sure if that is even a valid method. Please assist
Not sure if I understood your question, but:
Since you're requesting data associated with a primary key, you'll get either 0 or 1 element in Item.
So, if you aim to know if "you've found something or not", you can use Number(response.Item != null) and you'll get 1 in case of "something" and 0 in case of "nothing".
If, instead, your data contains a "count" attribute, then (await pullone(sessionId)).count should work.
Otherwise, you have to query your DB (but you'll get Items (plural) in your response) and use the length() function of the Items array you'll get in the response.

Can't access all values of array

I am getting a row from mysql into an array using node-mariasql.
When I print this array out using my Winston logger, I get this:
steamid=76561198053558238, tradePartnerId=93292510, tradeToken=T3dZTnlq, autoSendWinnings=1, profilePrivacy=0, earnings=0.00, lastKnownName=jdK jdK, avatar=https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/49/4955f3be7e9b9d16e8fc0b16ed2407ba9b4c563c.jpg, avatarLarge=https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/49/4955f3be7e9b9d16e8fc0b16ed2407ba9b4c563c_full.jpg
If I print out the value for "steamid", I get this as a return:
76561198053558238
However, if I print out the value for "autoSendWinnnings" or "profilePrivacy", I get "undefined" as a return.
Why is that? What am I doing wrong? I don't think it is a MySQL related issue, because if I print out the whole array, I obviously get all values.
Still, I'll append the relevant code here.
statements['get_user'] = sql.prepare('SELECT * FROM `users` WHERE steamid=:steamid');
function getUser(steamid, callback) {
sql.query(statements.get_user({ steamid: steamid }), { useArray: true }, function(err, rows) {
if(err)
logger.error('A MySQL error occured: ' + err);
callback(rows);
});
}
getUser('76561198053558238' function(user) {
logger.debug(user); // I get the whole array here
logger.debug(user.steamid); // I get the value for steamid here
logger.debug(user.autoSendWinnings); // I get undefined here
});
Thanks in advance,
I hope someone can help me.
Your callback receives an Array of result rows. For reasons unknown said Array has a property steamid.
Try
getUser('76561198053558238', function(users) {
logger.debug(users);
logger.debug(users[0].steamid);
logger.debug(users[0].autoSendWinnings);
});

What are MongoDB Modifiers and Operators?

I am working on a Meteor application and one of the features I'm building is a form that inserts a new document into an array (inserts a shipping address to a user's profile where a user can have multiple addresses). The error I keep getting is:
Exception while invoking method 'addAddress' Error: When the modifier option is true, validation object must have at least one operator
I have been unsuccessfully trying to figure out the answer on Stackoverflow, Github, etc. but could not find a solution. I now want to take the approach of understanding exactly what the error means - so my question is what exactly are modifier options and operators in MongoDB? From what I understand, modifiers provide constraints on what type of data is returned from a query, and operators are used to modify data. Are these definitions correct?
Does anyone know what the error I'm getting might mean? Here is my sample code:
My click event to capture data on a form and call a method to add an address:
Template.editAddress.events({
'click .addAddress': function(e, tmpl) {
e.preventDefault();
var currentUserId = Meteor.userId();
console.log(currentUserId);
var addressDetails = {
address: {
streetAddress: $('#streetAddress').val()
}
};
console.log(addressDetails);
Meteor.call('addAddress', addressDetails, currentUserId, function(error) {
if (error) {
alert(error.reason);
} else {
console.log('success!');
Router.go('Admin');
}
});
}
});
My method to insert the address:
Meteor.methods({
'addAddress': function(addressDetails, currUserId) {
var currentUserId = currUserId;
console.log('user to add address to is ' + currUserId);
Meteor.users.update(currentUserId, {$addToSet:
{
'address.streetAddress': addressDetails.streetAddress
}
});
}
});
Note that when I type that query in the console, it works:
db.users.update({_id: 'Qdf89k3fd93jfdk'}, {$addToSet: {'address.streetAddress': '12345 fake st'}});
Thank you in advance!
Your addressDetails object doesn't have a field streetAddress, so addressDetails.streetAddress returns undefined. Use addressDetails.address.streetAddress instead in the update. And also, like Joshua pointed out, use an object as selector with { _id: currUserId }. So the whole function should be:
Meteor.users.update( { _id: currentUserId }, {$addToSet:
{
'address.streetAddress': addressDetails.address.streetAddress
}
});
}
One more thing, you should not pass the userId from the client. Any method you define is callable from the client and like that, I would be able to call your method 'addAddress' from the browser console with any userId to update their address. Instead, use the this.userId object in method calls (see here) and check that it is not null, i.e. user is logged in.
if (! this.userId)
throw new Meteor.Error(401, "You must be logged in!");
var currentUserId = this.userId;
It looks like you're passing in the document id directly into the MongoDB query method, rather than constructing an object with an _id property with a value of said document id.
i.e try
var currentUserId = { _id: currUserId };

How to delete object instances from Parse users account that matching a property

What I want to do is delete an instance of a matchCenterItem object under a user account, based on the "searchTerm" property of the instance. I've tried setting it up according to Parse documentation, but it's giving me an error stating: Failed with: success/error was not called.
Parse.Cloud.define("deleteFromMatchCenter", function(request, response) {
var matchCenterItem = Parse.Object.extend("matchCenterItem");
var query = new Parse.Query(matchCenterItem);
query.containedIn('searchTerm', request.params.searchTerm);
query.equalTo('parent', Parse.User.current())
query.find().then(function(matchCenterItem) {
return Parse.Object.destroyAll(matchCenterItem);
}).then(function(success) {
console.log("Match Center Item deleted, sweet!");
}, function(error) {
console.error("Error deleting related Match Center Items!");
});
});
So the error is correct, you need to call success or error on the response object passed in to the function, like:
Parse.Object.destroyAll(matchCenterItem).then(function() {
response.success('ok');
}, function(err) {
response.error(err);
}

Check repeat objects in Parse.com with AngularJS

I would like to know if exist any way to check in a Parse.com database a repeat object, for example, I have this function:
$scope.addRecoDeseo = function(){
var DeseoObjeto = new DeseoModel();
DeseoObjeto.set("User",Parse.User.current());
DeseoObjeto.set("Deseo",$scope.recomendado);
DeseoObjeto.save(null, {
success: function(obj) {
alert('ok')
},
error: function(obj,error) {
alert("error")
}
});
}
are there any way to have a error if exist a object with the same User and Deseo?
You could use CloudCode to implement a unique field, check the answer here: Parse.com post

Categories