How can match an object to a query with Javascript/AngularJS? - javascript

I am trying to find a way to return the URL of a query based on whether or not the data given was found within that query output. This is what I am doing and what I am trying to do:
var homes = ["home1","home2","home3"]; // Given
var addresses = [query1,query2]; //Given only as URLs
for(var i = 0; i < homes.length; i++){
/*Find the matching query to JSON object where home object is stored*/
var theRightAddress = find(homes[i],addresses);
/*Make sure the variable is found*/
console.log(theRightAddress);
}
In the data in query1 and query2 should appear as objects like:
[home1, home7, home32] /* for query1 */
[home2, home3, home102] /* for query2 */
BUT, I am only given the urls to these queries. So, Query1 may appear something like the link https://foo/foo/foo/query1 and Query2 like https://foo/foo/foo/query2.
So, addresses is actually:
var addresses = ["https://foo/foo/foo/query1","https://foo/foo/foo/query1"];
I am simply trying to match the addresses with the homes (that are given). I have tried AngularJS HTTP GET requests, but I can't seem to return any of the results since you need to use promises. All I am really looking for is a way to implement find() such that it returns the correct URL and sets theRightAddress.
Ex.) find("home1",addresses) should return:
https://foo/foo/foo/query1
Ex.) find("home2",addresses) should return:
https://foo/foo/foo/query2
Ex.) find("home3",addresses) should return:
https://foo/foo/foo/query2

Related

Building a progressive query in Mongoose based on user input

I'm writing a simple REST API that is basically just a wrapper around a Mongo DB. I usually like to use the following query params for controlling the query (using appropriate safeguards, of course).
_filter=<field_a>:<value_a>,<field_b><value_b>
some values can be prepended with < or > for integer greater-than/less-than comparison
_sort=<field_c>:asc,<field_d>:desc
_fields=<field_a>,<field_b>,<field_c>
_skip=<num>
_limit=<num>
Anyway, the implementation details on these are not that important, just to show that there's a number of different ways we want to affect the query.
So, I coded the 'filter' section something like this (snipping out many of the validation parts, just to get to point):
case "filter":
var filters = req.directives[k].split(',');
var filterObj = {};
for(var f in filters) {
// field validation happens here...
splitFields = filters[f].split(':');
if (/^ *>/.test(splitFields[1])) {
filterObj[splitFields[0]] = {$gt: parseInt(splitFields[1].replace(/^ *>/, ''), 10)};
}
else if (/^ *</.test(splitFields[1])) {
filterObj[splitFields[0]] = {$lt: parseInt(splitFields[1].replace(/^ *</, ''), 10)};
}
else {
filterObj[splitFields[0]] = splitFields[1];
}
}
req.directives.filter = filterObj;
break;
// Same for sort, fields, etc...
So, by the end, I have an object to pass into .find(). The issue I'm having, though, is that the $gt gets changed into '$gt' as soon as it's saved as a JS object key.
Does this look like a reasonable way to go about this? How do I get around mongoose wanting keys like $gt or $lt, and Javascript wanting to quote them?

how to fetch all values in single variable using java script

i am retrieving the all values in a for loop but i want to insert those values in database using single variable.It possible to store all values to the single record.
var emailId;
//log.info("testing 1234 = "+tw.local.EntityProMasterList.listAllSelected);
for (var i = 0; i < tw.local.EntityProMasterList.listAllSelected.listLength; i++){
emailId = tw.local.EntityProMasterList.listAllSelected[i];
log.info("testing 1 = "+emailId.value);
}
log.info("testing 1 = "+emailId.value);
You can user JSON.stringify() and save it as string:
var holder = {};
holder.var1 = "var1";
holder.var2 = "var2";
log.info("holder:"+JSON.stringify(holder));
The output will be:
holder:{"var1":"var1","var2":"var2"}
I believe your question is - given a list of values, how can I insert those values into the database as separate entries. If this is correct there is a right way and a wrong way to do this.
The wrong way is to simply put all the SQL into a string and use one of the DB services in the system data toolkit to execute. Something like -
insert into table blah values(1, 2, 3, 4);
This would be wrong because you are open to SQL injection attacks. There is a different service for parameterized queries. This takes 1 or more SQL statements and a list of parameters to use in them. The details are documented in the service so I won't repeat them here. Basically you would modify your query to have the ? Character where you need the data from your array. You then create arrays of parameters that fill out the values on execution.

Adding parameters to URL, putting array in query string

Objective
I've built an interactive where people can choose six players to make their all-star team. When they click share to Twitter, my hope is to have a URL containing parameters of all six players something like website.com/?playerName=picked?playerName=picked so that people can share their teams
Question
What is the best way to append parameters to a URL?
How do you put an array into a query string?
You can use an array directly in a url, however you would need to serialize the array into a string. like this player[]=one&player[]=two
here is a little function to automate it.
when using url's you should always use encodeURIComponent to encode any non url friendly characters. The players are an array so we map over it and get a new array that has been encoded.
After that we simply need to join the array with &
const players = [
'player Name 1',
'playerName2',
'playerName3'
]
const parameterizeArray = (key, arr) => {
arr = arr.map(encodeURIComponent)
return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}
console.log(parameterizeArray('player', players))
edit
The only difference is the function declaration style, everything else is standard ES5
function parameterizeArray(key, arr) {
arr = arr.map(encodeURIComponent)
return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}
Cleaner:
website.com/?players=player1,player2,player3,player4
Then split the query to get result:
var arrayResult = query.players.split(",")

Get specific object from Parse (.com) query result by field without going back to DB

So say I do a query on Parse database and get a results object, with each result having a field place_id.
How can I then get a specific object by place_id from the results without actually going back to the database (want to minimise network traffic and db querying...)?
This is what my query will look like:
var LatestUpdate = Parse.Object.extend("LatestUpdate");
var query = new Parse.Query(LatestUpdate);
query.containedIn("place_id", arrayOfplaceIds);
query.find().then(
function(results){
// and then i want to do something like:
return results.findByField("place_id", 1234) // get a specific object from the result without going back to the database?
}
);
You have to loop through your results and find the object that matches your criteria. You can do this easily using underscore.js which is supported on the cloud:
var match = _.find(results, function(object){ return object.get("place_id") == 1234; });
Just make sure your have var _ = require('underscore'); on top of your js file.

Query with multiple OR using parse.com

I am using Parse.com (JS) for my current project. A simple thing in SQL is driving me nuts with Parse.com, I have read the documentation, but I must say I have trouble understanding correctly the "object" approach.
Anyway, what I need to do is to apply multiple "OR" to a query. Let's say I have three tables :
UserObject(uid, username, password)
ResponseObject(rid, _userid, _questionid, response) // not used here
QuestionObject(qid, questionTitle, _userid)
_userid are pointers to the User table
_questionid is a pointer to the Question table
I first need to select users starting with "mat" from the User table, I do :
var UserObject = Parse.Object.extend("UserObject");
var query = new Parse.Query(UserObject);
query. startsWith("username", "mat");\
query.find({
success: function(results) { etc...
In results I now have an array of the users I need. Now I need to select all the question in the Question table where _userid matches this array. I understand I can use the Parse.Query.or as follow :
var QuestionObject = Parse.Object.extend("QuestionObject");
var query1 = new Parse.Query(QuestionObject);
query1.equalTo("userid", results[0].get('uid'));
var query2 = new Parse.Query(QuestionObject);
query2.equalTo("userid", results[1].get('uid'));
var mainQuery = new Parse.Query.or(query1, query2);
mainQuery.find({...})
But I have no idea how big results is, and if I have 50 users back, I don't want to use Parse.Query.or 50 times ! So I am sure there is an easy solution, but I am stuck ! I'd like to pass directly "results" to the new query or something like that !
No need for Parse.Query.or(). Parse.Query provides containedIn() that will match if the value of an object's property is one among some array of values.
(The question states that userId on the Question object is a pointer. That's a great choice, but the name "userId" is a confusing choice. Is it an id or an object? I hope an object, and the remainder of this answer assumes that).
// results is an array of Parse.User from a prior query
var QuestionObject = Parse.Object.extend("QuestionObject");
var query = new Parse.Query(QuestionObject);
query.containedIn("userid", results);
query.find(...)
More fully, and with promises...
var userQuery = new Parse.Query("UserObject");
userQuery.startsWith("username", "mat");
userQuery.find().then(function(userObjects) {
var query = new Parse.Query("QuestionObject");
query.containedIn("userid", userObjects);
return query.find();
}).then(function(questions) {
// questions are Questions who's users' username begins with 'mat'
});

Categories

Resources