how to implement sort method in sails,js when i run in postman it give me error - sails.js

How to implement sort method in sails js when i run this code
Code :
try{
let sort = req.param('name')
let mysort = {}
mysort.name = sort;
// console.log(mysort)
let find = await dynamic.find().sort(mysort) //used to find All records from Database
console.log(find)
return res.status(200).json({
"success" : true,
"find" : find
})
}
Expecting = sorted database(records)
Any Solution for this?

Related

How to pull all product data from index in Algolia?

After reading the docs on how to search and browse an index with Algolia's Swift Client, it's not clear how I need to pull all product data from an index. In the documentation, it is stated that:
The search query only allows for the retrieval of up to 1000 hits. If
you need to retrieve more than 1000 hits (e.g. for SEO), you can
either leverage the Browse index method or increase the
paginationLimitedTo parameter
So I wrote the following:
let client = SearchClient(appID: "...", apiKey: "...")
var index: Index
index = client.index(withName: "products")
var productFeed:[Product] = []
let settings = Settings()
.set(\.paginationLimitedTo, to: 4500)
index.setSettings(settings) { result in
if case .success(let response) = result {
.....
}
}
Then to Browse:
index.browse(query: Query("")) { result in
if case .success(let response) = result {
do {
let products:[Product] = try response.extractHits()
DispatchQueue.main.async {
self.productFeed = products
}
}catch let error{
print("Hits decoding error :\(error)")
}
}
}
It would seem as though the two blocks of code would work together, but my productFeed array just returns 1000 records. Can someone explain what I am doing wrong here?
To retrieve all records from your index use the browseObjects method.
This method performs multiple consecutive browse method calls extracting all records from an index page by page.

Firebase's ref().child(stringPath: String) returning the entire top level collection

I'm trying to retrieve a specific child of my Firebase database using swiftUI. To do that I use the simple expression
func addListeners() {
let database = Database.database(url: "https://someUrl")
let ref = database.reference(withPath: "users")
let currentUserId = "u3Ebr6M3BAbP7PBSYYJ7q9kEe1l2"
let drivingTowardsRef = database.reference(withPath: "users/\(currentUserId)/drivingTowardsUsers")
print("Loading data from \(drivingTowardsRef)")
//THIS RIGHT HERE IS CAUSING THE PROBLEM
ref.observe(.childAdded) { snapshot in
print("Got TOP LEVEL data for user \(snapshot.key): \(String(describing: snapshot.value))")
}
//---------------------------------------
drivingTowardsRef.observe(.childAdded) { snapshot in
ref.child(snapshot.key).getData { (error, userSnapshot) in
if let error = error {
print(error)
} else {
print("Got arriving user data \(snapshot.key): \(String(describing: userSnapshot.value))")
}
}
}
}
The function will just return the entire database data
EDIT: The function returns the data from the first observer ref top level in this case users/ which in my case has two elements: niixi6iORjNn8gWq6tKvSi3Bxfc2, u3Ebr6M3BAbP7PBSYYJ7q9kEe1l2
Got arriving user data niixi6iORjNn8gWq6tKvSi3Bxfc2: Optional({
niixi6iORjNn8gWq6tKvSi3Bxfc2 = {
aproxTime = 0;
distance = 0;
latitude = "37.33070704";
longitude = "-122.03039943";
parkingMode = searching;
userId = niixi6iORjNn8gWq6tKvSi3Bxfc2;
username = testeroNumero;
};
u3Ebr6M3BAbP7PBSYYJ7q9kEe1l2 = {
aproxTime = 0;
distance = 0;
drivingTowardsUsers = {
niixi6iORjNn8gWq6tKvSi3Bxfc2 = {
approxTime = 0;
distance = "560.1447571016249";
};
};
latitude = "37.32984184";
longitude = "-122.02018095";
parkingMode = offering;
userId = u3Ebr6M3BAbP7PBSYYJ7q9kEe1l2;
username = cleoBadu;
};
The key for the child path I pass him seems to be correct but it's still returning the entire top level collection instead of the single item...
EDIT: The problem seems to be on the first observer which messes up the .getData() of the ref.child(snapshot.key). Is that even possible?
Just commenting out that ref.observe(.childAdded) will automatically make the second ref.child(snapshot.key) behave totally normally
What am I missing?
I could get the entire database as a single mega dictionary and then get the child I want from there but it doesn't seem really conventional, especially when google's library offers the possibility to not do that.
EDIT: I added a printing statement that prints the url of the database ref. If I then type in the url on my browser, it redirects me on the FRT database and landing me on the correct object. So the url it's generating is correct and works perfectly fine.
Still the object returned by the getData() is the entire db
SN: I removed all codable structs as that is not the problem, so the question is more focused on the actual problem
EDIT: Created a simple view as that. On a clean project it works on my project it doesn't. I guess it's some sort of configuration but's it's hard to look into it.
PROBLEM: Whatever child(string) I pass him it returns the entire top level data either way (replacing so snapshot.key). For example: I pass the key "something" -> all users are returned, I pass the key "" all users are returned
I just tried to reproduce the problem with (mostly) your code and data, but am not getting the same behavior.
I put the equivalent data into a database of mine at: https://stackoverflow.firebaseio.com/68956236.json?print=pretty
And used this code in Xcode 1.2 with Firebase SDK version 8.6.1:
let ref: DatabaseReference = Database.database().reference().child("68956236")
let currentUserId: String = "u3Ebr6M3BAbP7PBSYYJ7q9kEe1l2"
let drivingTowardsRef: DatabaseReference! = ref.child("\(currentUserId)/drivingTowardsUsers");
print("Loading data from \(drivingTowardsRef)")
drivingTowardsRef.observe(.childAdded) { snapshot in
ref.child(snapshot.key).getData { (error, userSnapshot) in
if let error = error {
print(error)
} else {
do {
//let parkingUser = try userSnapshot.data(as: ParkingUser.self)
print("Got data for user \(snapshot.key): \(String(describing: userSnapshot.value))")
} catch {
print("There has been an error while decoding the user location data with uid \(snapshot.key), the object to be decoded was \(userSnapshot). The decode failed with error: \(error)")
}
}
}
}
The output I get is:
Loading data from Optional(https://stackoverflow.firebaseio.com/68956236/u3Ebr6M3BAbP7PBSYYJ7q9kEe1l2/drivingTowardsUsers)
2021-08-27 10:39:09.578043-0700 Firebase10[36407:3458780] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed
Got data for user niixi6iORjNn8gWq6tKvSi3Bxfc2: Optional({
aproxTime = 0;
distance = 0;
latitude = "37.32798355";
longitude = "-122.01982712";
parkingMode = searching;
userId = niixi6iORjNn8gWq6tKvSi3Bxfc2;
username = testeroNumero;
})
As far as I can see this behavior is correct, but different from what you get. I hope knowing that I don't see the same behavior, and what versions I use, may be helpful to you.
This is not an issue with Firebase but rather client-side handling of the data returned, You’re expecting a Double within your Codable struct but supplying a String in the other end— Can you try:
public struct ParkingUser: Codable {
var latitude: String
var longitude: String
}

MongoKitten : Find using contains

I have started using MongoKitten (Swift) which is really nice, however, I can't find anywhere how to do a Mongo find looking for a partial string.
In Mongo, it would be:
db.users.findOne({"username" : {$regex : ".son."}});
Seems such a normal thing to do.
So after talking to the MongoKitten people on Slack I thought I would come back and answer the question. Code for Swift 4
func findDocsWith( str: String) -> CollectionSlice<Document>? {
do {
let server = try Server(Settings.server)
let database = server["YourDB"]
let pages = database["YourCollection"]
let query: Query = [
"url": RegularExpression(pattern: ".\(str).")
]
let matchingEntities: CollectionSlice<Document> = try pages.find(query)
print (try matchingEntities.count())
return matchingEntities
} catch {
print("error: unable to start rest service.\n")
return nil
}
}

Unable to query PG database using koa-pg middleware on Koa on localhost

In the past I've been able to connect to a postgres db using koa-pg middleware connected to a database hosted on Heroku, but I'm having problems connecting to a locally-hosted database.
Specifically, the error I have is TypeError: Cannot read property 'client' of undefined.
The following is my setup on the single-file app:
const koa = require('koa');
let route = require('koa-route'); // For calling specific routes
let request = require('koa-request'); // For RESTful requests
let paramify = require('koa-params');
var koaPg = require('koa-pg');
let pg = require('pg'); // .native;
let cors = require('koa-cors');
let parser = require('xml2js').parseString;
// pg.defaults.ssl = true;
route = paramify(route);
let param = route.param;
let get = route.get;
let app = koa();
let appPort = (process.env.PORT || 3000)
app.use(cors());
app.use(koaPg('postgres://localhost:5432/ttc_clustering_dev'));
And the following is the route where the issue lies:
app.use(route.get('/initialDefaultRouteQuery', function *() {
let options = {
url: 'http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a=ttc&r=60'
}
let xmlResponse = yield request(options)
let jsResponse = ''
parser(xmlResponse.body, function(err,result){
//Extract the value from the data element
jsResponse = result
if (err !== null) {
console.log(`Error: ${err}`)
} else {
console.log('Success in parsing from XML to JSON')
}
});
let i = 0
while (i < jsResponse.body.vehicle.length) {
let query_content = `INSERT INTO temp_records (route_id, bus_id, capture_time, geometry) VALUES ('60', '${jsResponse.body.vehicle[i].$.id}', ${Date.now() - (jsResponse.body.vehicle[i].$.secsSinceReport * 1000)}, ST_GeomFromText('POINT(${jsResponse.body.vehicle[i].$.lng} ${jsResponse.body.vehicle[i].$.lat})'))`
let result = yield pg.db.client.query_(query_content)
console.log('result:' + result)
i += 1;
}
this.body = 'Finished!'
}));
It appears I've used the proper setup according to the docs, but there's likely something I'm missing here. Does anyone else see where I'm falling flat?
The full file can be found here: https://github.com/brianbancroft/ttc-clustering/blob/add-records-to-db/server/app.js
Due to the docs it should be:
let result = yield this.pg.db.client.query_(query_content)
instead of
let result = yield pg.db.client.query_(query_content)
So the this. is missing.
And reviewing your code, you are explicitly requiring pg, so your code is calling that one instead the one from koa-pg. Therefore pg.db seems not to be defined. Makes sense?

CKQuery with CloudKit Issue

I'm very new to CloudKit and am simply trying to run the most basic query. I want to pull from RecordType "Users" and field type "Name" and have the name equal to my nameText label!
Please see my code below:
func getUserInformation() {
let Pred = NSPredicate(value: true)
let Query = CKQuery(recordType: "Namer", predicate: Pred)
let AgeOp = CKQueryOperation(query: Query)
AgeOp.database = self.Pub
AgeOp.recordFetchedBlock = {(record : CKRecord!) in
let Recorded : CKRecord = record!
self.nameText.text = Recorded.objectForKey("Name") as? String
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.Container = CKContainer.defaultContainer() as CKContainer
self.Pub = Container.publicCloudDatabase as CKDatabase
self.Container.accountStatusWithCompletionHandler {
accountStatus, error in
if error != nil {
print("Error: \(error?.localizedDescription)")
} else {
self.getUserInformation()
}
}
}
Users is a system table. You could add new fields to that, but it's advised not to do so. One of the main reasons is that you cannot query the Users recordType.
Besides that I see in your code that you query the recordType Namer and not Users. Is your question wrong or is your code wrong?
In the recordFetchedBlock you directly put the result in the .text. That block will be executed in a background thread. You should first go to the mainQueue. You could do that like this:
AgeOp.recordFetchedBlock = {(record : CKRecord!) in
NSOperationQueue.mainQueue().addOperationWithBlock {
let Recorded : CKRecord = record!
self.nameText.text = Recorded.objectForKey("Name") as? String
}
}
When there is no query match, then the .recordFetchedBlock will never be called. You should also set the .queryCompletionBlock
The query could return multiple records (if there are more people with the same name). In the recordFetchedBlock you should add records to an array. Then in the .queryCompletionBlock you could use that array.