Parse - Create an AND query of two OR queries - javascript

I need to do the following query in Parse.com (pseudo language):
select all posts where
(expired < today OR expired not exists)
AND
(owner is {user} OR commenter contains {user})
I know in Javascript I can create the two OR queries using Parse.Query.or, but since there doesn't seems to be a Parse.Query.and variant, I don't know how I can combine these two OR queries into a single query.
Other people have suggested to simply use equalTo multiple times to create AND statements, but this doesn't work for a composed OR query.

I'm not familiar with Parse and this is too long for a comment, but see below from the documentation; the last sentence in particular seems to be what you're after.
Compound Queries
If you want to find objects that match one of several queries, you can use Parse.Query.or method to construct a query that is an OR of the queries passed in. For instance if you want to find players who either have a lot of wins or a few wins, you can do:
var lotsOfWins = new Parse.Query("Player");
lotsOfWins.greaterThan("wins", 150);
var fewWins = new Parse.Query("Player");
fewWins.lessThan("wins", 5);
var mainQuery = Parse.Query.or(lotsOfWins, fewWins);
mainQuery.find({
success: function(results) {
// results contains a list of players that either have won a lot of games or won only a few games.
},
error: function(error) {
// There was an error.
}
});
You can add additional constraints to the newly created Parse.Query that act as an 'and' operator.

You can use both AND with OR like this. Attributes in the AND being the equalTo valuables.
const mainQuery = Parse.Query.or(
Parse.Query.and(lotsOfWins, fewWins2),
Parse.Query.and(lotsOfWins2, fewWins)
);
You can add as many as you like..
const lotsOfWins = new Parse.Query("CLASS");
lotsOfWins.equalTo('user', CurrentUser);
const fewWins = new Parse.Query("CLASS");
fewWins.equalTo('recipient', CurrentUser);

Related

Sequelize how to return result as a 2D array instead of array of objects?

I am using Sequelize query() method as follows:
const sequelize = new Sequelize(...);
...
// IMPORTANT: No changed allowed on this query
const queryFromUser = "SELECT table1.colname, table2.colname FROM table1 JOIN table2 ON/*...*/";
const result = await sequelize.query(queryFromUser);
Because I am selecting two columns with identical names (colname), in the result, I am getting something like:
[{ "colname": "val1" }, { "colname": "val2" }...], and this array contains values only from the column table2.colname, as it is overwriting the table1.colname values.
I know that there is an option to use aliases in the SQL query with AS, but I don't have control over this query.
I think it would solve the issue, if there was a way to return the result as a 2D array, instead of the array of objects? Are there any ways to configure the Sequelize query that way?
Im afraid this will not be possible without changes in the library directly connecting to the database and parsing its response.
The reason is:
database returns BOTH values
then in javascript, there is mapping of received rows values to objects
This mapping would looks something like that
// RETURNED VALUE FROM DB: row1 -> fieldName:value&fieldName:value2
// and then javascript code for parsing values from database would look similar to that:
const row = {};
row.fieldName = value;
row.fieldName = value2;
return row;
As you see - unless you change the inner mechanism in the libraries, its impossible to change this (javascript object) behaviour.
UNLESS You are using mysql... If you are using mysql, you might use this https://github.com/mysqljs/mysql#joins-with-overlapping-column-names but there is one catch... Sequelize is not supporting this option, and because of that, you would be forced to maintain usage of both libraries at ones (and both connected)
Behind this line, is older answer (before ,,no change in query'' was added)
Because you use direct sql query (not build by sequelize, but written by hand) you need to alias the columns properly.
So as you saw, one the the colname would be overwritten by the other.
SELECT table1.colname, table2.colname FROM table1 JOIN table2 ON/*...*/
But if you alias then, then that collision will not occur
SELECT table1.colname as colName1, table2.colname as colName2 FROM table1 JOIN table2 ON/*...*/
and you will end up with rows like: {colName1: ..., colName2: ...}
If you use sequelize build in query builder with models - sequelize would alias everything and then return everything with names you wanted.
PS: Here is a link for some basics about aliasing in sql, as you may aliast more than just a column names https://www.w3schools.com/sql/sql_alias.asp
In my case I was using:
const newVal = await sequelize.query(query, {
replacements: [null],
type: QueryTypes.SELECT,
})
I removed type: QueryTypes.SELECT, and it worked fine for me.

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 create a copy of mongoose's Aggregate object?

I need a way to duplicate and dynamically modify my requests to the database. With regular mongoose Query objects I can create a copy of the query with x = query.toConstructor() and later fire multiple requests with additional parameters, e.g.:
var sample = x().limit(5);
var totalCount = x().count();
However mongoose's Aggregate objects lack the toConstructor function. Is there any way to achieve same results with an Aggregate object?
The following solution worked for me well, though not so nice.
const withoutId = Model.aggregate().project({ _id: false });
const totalCount = Model.aggregate(withoutId.pipeline()).count('count');
Hope this will help at least others.

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'
});

parse.com search for partial string in array

I'm trying to search a Parse.com field which is an array for a partial string.
When the field is in String format I can do the following:
// Update the filtered array based on the search text and scope.
// Remove all objects from the filtered search array
[self.searchResults removeAllObjects];
// Filter the array using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.busnumber contains[c] %#", searchText];
self.searchResults = [NSMutableArray arrayWithArray:[self.objects filteredArrayUsingPredicate:predicate]];
This works, however the new field I want to search in is an Array.
It works when I change the it to the following:
PFQuery * query = [PFQuery queryWithClassName:#"Bus"];
[query whereKey:#"route" equalTo:[NSString stringWithFormat:#"%#", searchText]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
NSLog(#"Objects: %#", objects);
if (error)
{
NSLog(#"ERROR: %#", error.localizedDescription);
}
else
{
[self.searchResults removeAllObjects];
[self.searchResults addObjectsFromArray:objects];
[self.searchDisplayController.searchResultsTableView reloadData];
}}];
However I need the exact String for this.
I want to be able to search for parts of a string though, but when I change it to:
[query whereKey:#"route" containsString:[NSString stringWithFormat:#"%#", searchText]];
I get:
[Error]: $regex only works on string fields (Code: 102, Version: 1.7.4)
Any ideas? Thanks :)
What you've attempted is rational, but the string qualifiers on PFQuery work only on strings.
I've seen this theme frequently on SO: PFQuery provides only basic comparisons for simple attributes. To do anything more, one must query for a superset and do app level computation to reduce the superset to the desired set. Doing so is expensive for two reasons: app-level compute speed/space, and network transmission of the superset.
The first expense is mitigated and the second expense is eliminated by using a cloud function to do the app level reduction of the superset. Unless you need the superset records on the client anyway, consider moving this query to the cloud.
Specific to this question, here's what I think the cloud function would resemble:
// very handy to have underscore available
var _ = require('underscore');
// return Bus objects whose route array contains strings which contain
// the passed routeSubstring (request.params.routeSubstring)
Parse.Cloud.define("busWithRouteContaining", function(request, response) {
// for now, don't deal with counts > 1k
// there's a simple adjustment (using step recursively) to get > 1k results
var query = new Parse.Query("Bus");
query.find().then(function(buses) {
var matching = _.select(buses, function(bus) {
var route = bus.get("route");
var routeSubstring = request.params.routeSubstring;
return _.contains(route, function(routeString) {
return routeString.includes(routeSubstring);
});
});
response.success(matching);
}, function(error) {
response.error(error);
});
});
If you do decide to perform the reduction on the client and need help with the code, I can edit that in. It will be a pretty simple switch to predicateWithBlock: with a block that iterates the array attribute and checks rangeOfString: on each.

Categories

Resources