Javascript / Parse: Follow wont return 'to' value - javascript

I am trying to get all of the users that are following the current user. From some reason Parse returns the username as undefined in the 'to' field but I am able to retrieve the user name from the 'from' field like so:
var query = new Parse.Query("Follow");
query.equalTo("to", Parse.User.current());
query.find({
success: function(users){
for (var i = 0; i < users.length; i++) {
console.log(users[i].get('from').get('username')) // returns current username
console.log(users[i].get('to').get('username')) / returns undefined
}
}
});
But those values do exist and there is a username. I am able to get the value using the fetch method but I am curious as to why this approach doesn't work. Thoughts?

From Doc, you're not getting the actual object, but the ref to that object:
Internally, the Parse framework will store the referred-to object in just one place, to maintain consistency. ......
And
By default, when fetching an object, related Parse.Objects are not
fetched. These objects' values cannot be retrieved until they have
been fetched like so:
// Here, post is something similar to your `users[i].get('to')`
var post = fetchedComment.get("parent");
// So you need to fetch it again to get its real object.
post.fetch({
success: function(post) {
var title = post.get("title");
}
});
So what you get from users[i].get('to') is a reference to that user object. You can either fetch it again.

Related

Search value in JSON and return to console

I am trying to search a value in a JSON file using a input field from the user through the browser.
A sample JSON object from the array of objects looks like this:
I have an event listener to wait for click from the user. After the user clicks the function will go to the api json site and retrieve all the data.
Next I would like to search through that JSON data for what the user typed in.
Example:
user input: "Cannonball"
expected output: 196 (buy_average)
However I am unable to figure out how to search through the object array.
Here's what I got:
the parameter "data" is the JSON objects that was retrieved from API. I know that works properly because I'm able to display it in the console.
function renderHTML(data) {
var searchVal = document.getElementById("search").value;
console.log(searchVal);
for (i=0; i<data.length; i++) {
if (data["i"].name == searchVal) {
console.log(data["i"].buy_average);
}
}
};
As of right now I'm just trying to figure how to look through an object array after retrieving it from the web and display it to the console.
When I click on the button nothing in the console appears to be happening except for the user's input. How can I fix this?
Try not using i as a string - use it as an integer instead:
if (data[i].name == searchVal) {
console.log(data[i].buy_average);
}
If data is an object, the length property will give you undefined. You can get the values using Object.values() and then iterate over the properties.
let data = {
0:{ id:0,name:"aa" },
1:{ id:1,name:"Cannonball"},
2:{ id:2,name:"xx" },
};
let searchVal = "Cannonball";
Object.values(data).forEach(e=>{
if(e.name === searchVal){
console.log("This is the object: ");
console.log(e);
}
});

How to get to request parameters in Postman?

I'm writing tests for Postman which in general works pretty easily. However, I now want to access some of the data of the request, a query parameter to be exact.
You can access the request URL through the "request.url" object which returns a String. Is there an easy way in Postman to parse this URL string to access the query parameter(s)?
The pm.request.url.query.all() array holds all query params as objects.
To get the parameters as a dictionary you can use:
var query = {};
pm.request.url.query.all().forEach((param) => { query[param.key] = param.value});
I have been looking to access the request params for writing tests (in POSTMAN). I ended up parsing the request.url which is available in POSTMAN.
const paramsString = request.url.split('?')[1];
const eachParamArray = paramsString.split('&');
let params = {};
eachParamArray.forEach((param) => {
const key = param.split('=')[0];
const value = param.split('=')[1];
Object.assign(params, {[key]: value});
});
console.log(params); // this is object with request params as key value pairs
edit: Added Github Gist
If you want to extract the query string in URL encoded format without parsing it. Here is how to do it:
pm.request.url.getQueryString() // example output: foo=1&bar=2&baz=3
pm.request.url.query returns PropertyList of QueryParam objects. You can get one parameter pm.request.url.query.get() or all pm.request.url.query.all() for example. See PropertyList methods.
It's pretty simple - to access YOUR_PARAM value use
pm.request.url.query.toObject().YOUR_PARAM
Below one for postman 8.7 & up
var ref = pm.request.url.query.get('your-param-name');
I don't think there's any out of box property available in Postman request object for query parameter(s).
Currently four properties are associated with 'Request' object:
data {object} - this is a dictionary of form data for the request. (request.data[“key”]==”value”) headers {object} - this is a dictionary of headers for the request (request.headers[“key”]==”value”) method {string} - GET/POST/PUT etc.
url {string} - the url for the request.
Source: https://www.getpostman.com/docs/sandbox
Bit late to the party here, but I've been using the following to get an array of url query params, looping over them and building a key/value pair with those that are
// the message is made up of the order/filter etc params
// params need to be put into alphabetical order
var current_message = '';
var query_params = postman.__execution.request.url.query;
var struct_params = {};
// make a simple struct of key/value pairs
query_params.each(function(param){
// check if the key is not disabled
if( !param.disabled ) {
struct_params[ param.key ] = param.value;
}
});
so if my url is example.com then the array is empty and the structure has nothing, {}
if the url is example.com?foo=bar then the array contains
{
description: {},
disabled:false
key:"foo"
value:"bar"
}
and my structure ends up being { foo: 'bar' }
Toggling the checkbox next to the property updates the disabled property:
have a look in the console doing :
console.log(request);
it'll show you all you can get from request. Then you shall access the different parameters using request., ie. request.name if you want the test name.
If you want a particular element in the url, I'm afraid you'll have to use some coding to obtain it (sorry I'm a beginner in javascript)
Hope this helps
Alexandre
Older post, but I've gotten this to work:
For some reason the debugger sees pm.request.url.query as an array with the items you want, but as soon as you try to get an item from it, its always null. I.e. pm.request.url.query[0] (or .get(0)) will return null, despite the debugger showing it has something at 0.
I have no idea why, but for some reason, it is not at index 0, despite the debugger claiming it is. Instead, you need to filter the query first. Such as this:
var getParamFromQuery = function (key)
{
var x = pm.request.url.query;
var newArr = x.filter(function(item){
return item != null && item.key == key;
});
return newArr[0];
};
var getValueFromQuery = function (key)
{
return getParamFromQuery(key).value;
};
var paxid = getValueFromQuery("paxid");
getParamFromQuery returns the parameter with the fields for key, value and disabled. getValueFromQuery returns just the value.

parse is still alive, but how to query by 'index'

I found that Parse is now supported by the Buddy platform, but all the forum/help files from the old Parse website are gone...
What i would like to do is query for one row in a table by row number/index.
I now do this, but it seems inefficient to me to get all data and then select the row (although it works fine):
var thisRow = Parse.Object.extend(GlobTable);
var query= new Parse.Query(thisRow);
query.descending('updatedAt');
query.find({
success: function(results) {
var object = results[RowNumberThatINeed];
//etc using object
#Ran, thanks! Somehow it doesn't work, Parse will store '1' for every row: 1,1,1,1. But it saves all other data ok.
var Object = Parse.Object.extend(LocTable);
var obj = new Object();
obj.set("User", LocUser);
obj.set("Happened", d);
obj.set("Happy", b);
obj.set("Learned",a);
obj.set("ConnectedTo",c);
obj.increment("rowIndex");
obj.save({
success: function(obj) {
updateDatabase();
alert("Your data is saved");
},
error: function(obj, err) {
alert("Your data was not saved. Sorry..." + err);
}
});
you solution will work but you will experience a lot performance issues when your table will growth.
What i suggest to you is the following solution:
Add another field to your GlobTable of type integer. This field will be incremental field and will store your row index (let's call this field rowIndex)
Each time you save a new object to this table make sure you increment this field by using the following command:
object.increment("rowIndex");
Now your query should look like the following:
var thisRow = Parse.Object.extend(GlobTable);
var query= new Parse.Query(thisRow);
query.equalTo("rowIndex",RowNumberThatINeed);
query.first().then(function(result){
// do something with the result
},function(error){
// error handling
});
If you want event better performance you can create index (in MongoDb) on your rowIndex.
In my code snippets i use Promises according to the best practices.
I use first and not find because there will always be one object for this index

How to get firebase id

Anyone know how to get the Firebase unique id? I've tried name(), name, key, key(). Nothing works.
I am able to see the data but I have no idea how to get the id back. I need it.
//Create new customers into firebase
function saveCustomer(email) {
firebase.database().ref('/customers').push({
email: email
});
firebase.database().ref('/customers').on("value", function(snapshot) {
console.log(snapshot.val());
console.log(snapshot.value.name());
}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
The call to push will return a Firebase reference. If you are using the Firebase 3 API, you can obtain the unique key of the pushed data from the reference's key property:
var pushedRef = firebase.database().ref('/customers').push({ email: email });
console.log(pushedRef.key);
The key for the pushed data is generated on the client - using a timestamp and random data - and is available immediately.
Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it.
The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated:
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();
Documentation.
but this method won't work when you also need the id beforehand
for example to save it in the database itself.
Firebase suggests this:
// Add a new document with a generated id.
var newCityRef = db.collection("cities").doc();
--for some reason, push() and key() didn't work for me. also in this case the reference contains the whole path. so need a different method for getting the id.
Doing this below helped to get the id from the reference and use it.
const ref = db.collection('projects').doc()
console.log(ref.id) // prints the unique id
ref.set({id: ref.id}) // sets the contents of the doc using the id
.then(() => { // fetch the doc again and show its data
ref.get().then(doc => {
console.log(doc.data()) // prints {id: "the unique id"}
})
})

Is it possible to retrieve a record from parse.com without knowing the objectId

See the sample code below - in this case, the objectId for the record I am trying to retrieve is known.
My question is, if I don't know the Parse.com objectId, how would I implement the code below?
var Artwork = Parse.Object.extend("Artwork");
var query = new Parse.Query(Artwork);
query.get(objectId, {
success: function(artwork) {
// The object was retrieved successfully.
// do something with it
},
error: function(object, error) {
// The object was not retrieved successfully.
// warn the user
}
});
Query.get() is used when you already know the Parse object id.
Otherwise, one can use query.find() to get objects based on the query parameters.
Sure, you can use Parse Query to search for objects based on their properties.
The thing that wasn't clear to me in the documentation is that once you get the object in the query, you would need to do:
With Query (can return multiple objects):
artwork[0].get('someField');
With 'first' or 'get':
artwork.get('someField');
You cannot do something like artwork.someField like I assumed you would

Categories

Resources