Query with multiple OR using parse.com - javascript

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

Related

Substring in Key parameter

I am working on my CouchDB project, where I want to create a specific view for my database.
It has proven that one of my key parameters has an ID as part of its name, but the other part is unique. ex "unique_ID_unique":"Value".
So brute force solutions like changing the name and/or how it is saved is not preferred.
To make it clear the ID is different for every entry (date).
I tried to modify it by using regex rules but it returns NULL for the key part.
emit(doc[/_unique$/], doc['something.else']);
Does someone have any idea why it is like that?
P.S: I already had a question like this yesterday, but due to the insufficient information that I gave, it led to wrong answers and I had to delete it.
Let's say you have a function that extract the unique key from a particular one:
var key = "blabla_120391029301923_blabla";
var keySplitted = key.split("_"); //Value: ["blabla","120391029301923","blabla"]
var uniqueKey = keySplitted[2]; //Value: blabla
From this, you can create a view what will map each documents and index them with your key.
function(doc){
var keySplitted = doc._id.split("_");
if(keySplitted.length == 3){
emit(keySplitted[2]);
}
}
The previous map ids from this:
evening_01012018_food
morning_02012018_musc
evening_01022018_food
To this:
food
musc
food
UPDATE
From offline discussion, I was able to understand that the objects to index had this content:
{
"_id": "doc_1",
"_rev": "1-89d017d9e5c82ee56d9beec2756fec99",
"type": "googrtt",
"ssrc_3685071425_send.bytesSent": "33621"
}
So with this document, the properties had to be split.
The final view content looks like this:
function (doc) {
for(key in doc){
var splitKey= key.split('_');
if(splitKey.length === 3){
emit(splitKey[2],doc[key]);
}
}
}

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

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

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.

Parse - Create an AND query of two OR queries

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

Javascript parse query

I'm having trouble with the following query. I'm pretty sure all the keys are right but the query isn't returning any objects. The problem line is:
query.equalTo("author", Parse.User.current());
If I take that line out then it returns me a random user's object, but I want this user's object. if I leave that line in I get no objects.
var query = new Parse.Query("personalInfoObject");
console.log(Parse.User.current().getUsername());
query.equalTo("author", Parse.User.current());
query.find({
success: function(results) {
// results is an array of Parse.Object
var obj=results[0];
console.log(obj)
},
User looks like a complex object. If author is a simple string, that comparison won't find anything. I see that you're printing out the username to the log, perhaps that's what you want to use for the where clause. It's hard to know without the structure of the objects.

Categories

Resources