r.table('table').filter({thing : 'thing'}).run(conn, function(err, result) {}) returning undefined - rethinkdb

So I,m trying to filter my database for names with this code:
r.table('Profiles').filter({mcname : user}).run(connection, function (err, profiles) {
console.log(r.table("Profiles").filter({mcname : user}).toString())
if (profiles.length == 0 || profiles == null) {
message.channel.send('No one was found by this name!')
} else if (profiles.length == 1) {
message.channel.send(`**${profiles[0].mcname}** is the IGN of **${profiles[0].name}!**`)
} else {
for (let i = 0; i < profiles.length; i++) {
embed.setTitle(`Here are the users I found with that IGN! Total(${profiles.length})`)
embed.addField(profiles[i].name, profiles[i].mcname)
}
message.channel.send(embed)
}
})
But it does not return any results.
I was expecting an array because that is what it returns in the database explorer, but treating it like an array just returns undefined, and printing it raw shows the connection info.
Any way to see the results and not connection info, or just print them to an array if it does not already?

r.table('Profiles').filter({mcname : user}) will return you a cursor.
If you want an array, you have to use .coerceTo('array'):
r.table('Profiles').filter({mcname : user}).coerceTo('array').run(...)
https://www.rethinkdb.com/api/javascript/coerce_to/

Related

"invalid sequence of tokens near ['for']" error in painless script query

I am getting error while executing this script query using Nest library in .net:
new ScriptQuery
{
Lang = "painless",
Source = "(!doc[params.headquartersCoordinatesField].empty && doc[params.headquartersCoordinatesField].arcDistance(params.latitude, params.longitude) * 0.000621371 <= params.maxDistance) || (!doc[params.offices].empty && (for (def office : doc[params.offices].values){if(office.coordinates).arcDistance(params.latitude, params.longitude) * 0.000621371 < =params.maxDistance{return true;}}))",
Params = new Dictionary<string, object>
{
{"headquartersCoordinatesField", Field<Provider>(f => f.Headquarters.Coordinates)},
{"offices", Field<Provider>(f => f.Offices)},
{"latitude", _latitude},
{"longitude", _longitude},
{"maxDistance", 50}
}
}
This is the error I get :
ServerError: Type: search_phase_execution_exception Reason: "all shards failed" CausedBy: "Type: script_exception Reason: "compile error" CausedBy: "Type: illegal_argument_exception Reason: "invalid sequence of tokens near ['for']." CausedBy: "Type: no_viable_alt_exception Reason: "no_viable_alt_exception: null""""
I also tried boolean variable inside loop and try to return that at the end but I get the same error.
I tried simple for loop with counter (i) to check the syntax but same error. So it seems like anything I use inside loop is returning error.
Can someone help to find the correct syntax ? Thanks in advance.
You cannot have a for loop inside a condition, it doesn't make sense.
Here is how your script should look like:
def hqCoordExist = !doc[params.headquartersCoordinatesField].empty;
def distToHq = doc[params.headquartersCoordinatesField].arcDistance(params.latitude, params.longitude);
if (hqCoordExist && distToHq * 0.000621371 <= params.maxDistance) {
return true;
}
def officesExist = !doc[params.offices].empty;
if (officesExist) {
for (def office : doc[params.offices].values) {
def distToOffice = office.coordinates.arcDistance(params.latitude, params.longitude);
if (distToOffice * 0.000621371 <= params.maxDistance) {
return true;
}
}
}
return false;
This worked for me. I had to check key and size of offices param. :
if(!doc[params.headquartersCoordinatesField].empty && doc[params.headquartersCoordinatesField].arcDistance(params.latitude, params.longitude) * 0.000621371 <= params.maxDistance)
{
return true;
}
def officesCollection = new ArrayList();
if(doc.containsKey(params.offices) && doc[params.offices].size() > 0)
{
officesCollection = doc[params.offices].value;
for (def office : officesCollection)
{
def distToOffice =
office.coordinates.arcDistance(params.latitude, params.longitude);
if (distToOffice * 0.000621371 <= params.maxDistance)
{
return true;
}
}
}
return false;

Filter on Tree or Nested Data

I have seen in one of the issues "Filter on Tree or Nested Data #1562" Oli has mentioned that
Hey #fr0z3nfyr
Filtering is supported on tree child nodes since version 4,2
Cheers
Oli :)
I am unable to find any example or the code to search nested data.
My code works perfectly fine for flat tables, but with nested tables it only works for the root node.
//data - the data for the row being filtered
//filterParams - params object passed to the filter
var match = false;
for (var key in data) {
if (data[key] != null) {
if ((data[key]).indexOf(filterParams.value) != -1) {
match = true;
}
}
}
return match;
}
function updateFilter(){
if ($("#filter-field").val() == "All Columns") {
table.setFilter(matchAny,{ value: $("#filter-value").val()});
} else {
table.setFilter($("#filter-field").val(), "like", $("#filter-value").val());
}
//var filter = $("#filter-field").val() == "All Columns" ? matchAny : $("#filter-field").val() ;
}```
Oli could you please point me to an example where Nested data filtering is supported
I was able to solve this, but by re-setting table data with filtered value and also the tree structure is not maintained in the filtered list. I can maintain the tree structure with some changes in code, but this flat looks more like what I needed once filtering is done.
// This method iterates through the dataRows and its tree children and call a recursive function which creates the filtered table data.
function updateFilter() {
var filtertableData = [];
table.getRows().filter(function (row) {
var rootData = row.getData();
rootData._children = [];
matchData(rootData, filtertableData);
var childRows = row.getTreeChildren();
searchForChildRows(rootData,childRows,filtertableData);
while (childRows.length != 0) {
for (var i = 0; i < childRows.length; i++) {
var childrow = childRows[i];
var childData = childrow.getData();
childData._children = [];
childRows = childrow.getTreeChildren();
searchForChildRows(childData,childRows,filtertableData);
}
}
});
table.setData(filtertableData);
}
function matchData(rootData, filtertableData, childdata) {
if (typeof childdata === "undefined") {
for (var key in rootData) {
console.log(key);
console.log(allVisibleCBSCols);
if (rootData[key] != null && typeof rootData[key] == 'string' && allVisibleCBSCols.includes(key)) {
if ((rootData[key]).indexOf($("#filter-value-Project").val()) != -1) {
filtertableData.push(rootData);
break;
}
}
}
} else {
for (var key in childdata) {
if (childdata[key] != null && typeof childdata[key] == 'string' && allVisibleCBSCols.includes(key)) {
if ((childdata[key]).indexOf($("#filter-value-Project").val()) != -1) {
//rootData._children.push(childdata);
filtertableData.push(childdata);
break;
}
}
}
}
}
function searchForChildRows(rootData,childRows,filtertableData) {
for (var i = 0; i < childRows.length; i++) {
var childrow = childRows[i];
var childData = childrow.getData();
childData._children = [];
matchData(rootData,filtertableData,childData);
}
}

Why does Spring Data fail on date queries?

I have records in my mongodb which are like this example record.
{
"_id" : ObjectId("5de6e329bf96cb3f8d253163"),
"changedOn" : ISODate("2019-12-03T22:35:21.126Z"),
"bappid" : "BAPP0131337",
}
I have code which is implemented as:
public List<ChangeEvent> fetchChangeList(Application app, Date from, Date to) {
Criteria criteria = null;
criteria = Criteria.where("bappid").is(app.getBappid());
Query query = Query.query(criteria);
if(from != null && to == null) {
criteria = Criteria.where("changedOn").gte(from);
query.addCriteria(criteria);
}
else if(to != null && from == null) {
criteria = Criteria.where("changedOn").lte(to);
query.addCriteria(criteria);
} else if(from != null && to != null) {
criteria = Criteria.where("changedOn").gte(from).lte(to);
query.addCriteria(criteria);
}
logger.info("Find change list query: {}", query.toString());
List<ChangeEvent> result = mongoOps.find(query, ChangeEvent.class);
return result;
This code always comes up empty. The logging statement generates a log entry like:
Find change list query: Query: { "bappid" : "BAPP0131337", "changedOn" : { "$gte" : { "$date" : 1575418473670 } } }, Fields: { }, Sort: { }
Playing around with variants of the query above in a database which has the record above gets the following results we get.
Returns records:
db["change-events"].find({ "bappid" : "BAPP0131337" }).pretty();
Returns empty set:
db["change-events"].find({ "bappid" : "BAPP0131337", "changedOn" : { "$gte" : { "$date" : 1575418473670 } } }).pretty();
Returns empty set:
db["change-events"].find({ "bappid" : "BAPP0131337", "changedOn" : { "$lte" : { "$date" : 1575418473670 } } }).pretty();
The record returned without the date query should be non empty on one of the two above. But it is empty on both.
What is wrong here?
Since the collection name change-events is different then Class name ChangeEvent so you have to pass the collection name in the find query of mongoOps as below:
List<ChangeEvent> result = mongoOps.find(query, ChangeEvent.class, "change-events");
I have tried it replicating and found that your query without dates in where clause also not working i.e:
Criteria criteria = null;
criteria = Criteria.where("bappid").is(bappid);
Query query = Query.query(criteria);
And the find query on mongoOps as below:
List<ChangeEvent> result = mongoTemplate.find(query, ChangeEvent.class);
Will not work, becuase collection name is missing, below query with collection name execute fine:
List<ChangeEvent> result1 = mongoTemplate.find(query, ChangeEvent.class, "changeEvents");
For details explanation of above discussion you can find out at my Github repo: https://github.com/krishnaiitd/learningJava/blob/master/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/main/Application.java#L157

How to check if the user doesn't select any item in the list?

I have a list view that list the activities. I have a way to get the selected values. What I don't know is how can I check if the user doesn't select any items from the list. How can I do this?
This is how I populate my list this will return at least 5-20 activities:
public void Get_Activities()
{
try
{
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var getActivity = conn.QueryAsync<ActivityTable>("SELECT * FROM tblActivity WHERE Deleted != '1' ORDER BY ActivityDescription");
var resultCount = getActivity.Result.Count;
if (resultCount > 0)
{
var result = getActivity.Result;
lstActivity.ItemsSource = result;
lstActivity.IsVisible = true;
}
else
{
lstActivity.IsVisible = false;
}
}
catch (Exception ex)
{
//Crashes.TrackError(ex);
}
}
And this is how I get the values of the selected items on my list:
foreach(var x in result)
{
if (x.Selected)
{
// do something with the selected items
}
}
My question is like this
if(list.selecteditemcount == 0){
DisplayAlert("Error","Please select atleast 1 item","Ok");
}
In xamarin projects you can use Linq (using System.Linq). With Linq it's really easy to filter your list like that:
if(!list.Any(x => x.Selected == true))
{
// DisplayAlert...
}
This basically checks if any of your items has the value Selected='true'
Or without Linq you can do something like this:
if(list.FindAll(x => x.Selected).Count() == 0)
{
//DisplayAlert...
}
Use this
if (result.Any(x => x.Selected))
{
}
else
{
await DisplayAlert("Application Error", "Please choose at least one(1) activity", "Ok");
}

How to cast swiftyjson value if sometimes is detected as int and other as string

I am getting the login info using alamofire and swiftyjson
Alamofire.request(.POST, postsEndpoint, parameters: newPost)
.responseSwiftyJSON({ (request, response, json, error) in
in my post response i have the value
json["id_usuario"]
the problem is that, when the value is -1 or 0 (zero) it can be obtained as int
using
let idUser = json["id_usuario"].int
and example of the reponse with the value in -1
{
"id_usuario" : -1
}
and the response when the value is greater than, a success login
{
"estado" : "Jalisco",
"plan_activo" : "0",
"datos_registro_completos" : 1,
"plan" : 0,
"genero" : "H",
"id_usuario_openpay" : "annvwl3didjylvex0wzh",
"fb_id" : "10205386840402780",
"email" : "steel.edward#hotmail.com",
"postal_code" : "44630",
"address" : "Nueva Escocia #1514 Interior 106",
"nombres" : "Steel Edward",
"app_mat" : "George",
"app_pat" : "Vázquez",
"ciudad" : "Guadalajara",
"id_usuario" : "204",
"admin" : "1",
"phone_number" : "3334691505"
}
but if the value is greater than 0 returns a nil and only could be obtained as string
let idUser = json["id_usuario"].string
my final code works and looks like this
if let idUser = json["id_usuario"].int {
if(idUser == -1) {
//specific error from the server
} else if(idUser == 0) {
//another specific error from the server
}
} else if let idUser = json["id_usuario"].string {
if(idUser != "") {
//success
}
}
i would like to store the value always as Int and perform the validation using it, and to have a code like this
if(idUser == -1) {
//specific error from the server
} else if(idUser == 0) {
//another specific error from the server
} else if (idUser > 0) {
//success
}
var id = 0
if let num = json["id_usuario"].int {
id = num
} else if let str = json["id_usuario"].string,
let num = Int(str) {
id = num
}
//
// do something with id, which is an Int value
if you own the server code, you are better to find a bug there ....
This was my first solution not using Swifty-JSON
let id_usuario_object:NSObject = jsonData.valueForKey("id_usuario") as! NSObject
var id_usuario:Int
if ( id_usuario_object.isKindOfClass(NSString) ) {
let id_usuario_string:NSString = jsonData.valueForKey("id_usuario") as! NSString
id_usuario = Int(id_usuario_string.intValue)
} else {
id_usuario = jsonData.valueForKey("id_usuario") as! NSInteger
}
The problem resides in the JSON response from the PHP...
Before
echo json_encode( $results);
After
echo json_encode( $results, JSON_NUMERIC_CHECK );

Resources