hey i'm creating an api to return users with their profile
i have two table from two separate database , users and profiles
fn handle(
&mut self,
query_strings: SearchUsersQueryStrings,
_: &mut SyncContext<Self>,
) -> Self::Result {
let gateway_conn: &PgConnection = &self.1.get().unwrap();
let own_conn: &PgConnection = &self.0.get().unwrap();
let pattern = format!("%{}%", query_strings.username);
let found_users = users
.filter(username.like(pattern))
.get_results::<User>(gateway_conn)?;
let profile = Profile::belonging_to(&found_users)
.load::<Profile>(own_conn)?
.grouped_by(&found_users);
let data = found_users.into_iter().zip(profile).collect();
Ok(data)
}
the bad thing here is data type result is , that is so ugly to parse
[
[
{
"id": 22,
"username": "412212512",
"email": "1231q1222122#gmail.com",
"avatar": null,
"created_at": "2022-02-21T09:31:29.855851"
},
[
{
"id": 3,
"user_id": 22,
"status": "qqq",
"description": "xxx",
"created_at": "2022-03-07T22:53:17.491532",
"updated_at": null,
"deleted_at": null
}
]
],
[
{
"id": 25,
"username": "1412drew212512",
"email": "1231q11srew222122#gmail.com",
"avatar": null,
"created_at": "2022-02-21T10:37:04.588795"
},
[]
],
]
but i want something like this:
[
{
"id": 22,
"username": "1412212512",
"email": "1231q1222122#gmail.com",
"avatar": null,
"created_at": "2022-02-21T09:31:29.855851",
"profile": {
"id": 3,
"user_id": 22,
"status": "qqq",
"description": "xxx",
"created_at": "2022-03-07T22:53:17.491532",
"updated_at": null,
"deleted_at": null
},
....
]
if i use load func on profile query it will return Vec<Profile> but each user has a single record of Profile , if i dont use load and use first instead then i could not use grouped_by over it
Create a struct named UserAPI like this:
pub struct UserAPI {
#[serde(flatten)]
pub user: User,
pub profile: Profile,
}
Then after zipping data do this:
fn handle(
&mut self,
query_strings: SearchUsersQueryStrings,
_: &mut SyncContext<Self>,
) -> Self::Result {
let gateway_conn: &PgConnection = &self.1.get().unwrap();
let own_conn: &PgConnection = &self.0.get().unwrap();
let pattern = format!("%{}%", query_strings.username);
let found_users = users
.filter(username.like(pattern))
.get_results::<User>(gateway_conn)?;
let profile = Profile::belonging_to(&found_users)
.load::<Profile>(own_conn)?
.grouped_by(&found_users);
let data = found_users.into_iter().zip(profile).collect();
let users_with_profile: Vec<UserAPI> = data
.into_iter()
.map(|(user, profile)| {
UserAPI {
user,
profile,
}
})
.collect();
Ok(users_with_profile)
}
Related
I am working on an NODE JS based application. Trying to figure out any easy method to get my expected result. Had tried few ways, but after reframing the JSON content not able to add the key state.
My content JSON content is in this format
[
{
"item": {
"property1": "aa",
"property2": "22"
},
"state": {
"item": {
"state": "AS",
"country": "US",
"reason": "1"
}
},
"province": {
"item": {
"name": "AS",
"method": "table",
"conf": "3"
}
}
},
...
]
Requirement is to format state as below,
{
...
"state": [
{
"item": {
"state": "AS",
"country": "US",
"reason": "1"
}
}
],
...
}
I want to format the state content. The content is expected to be an array of JSON content. After formatting state, the orginal json content need to be modified with the new content of state. The issue faced here is after formatting not able to add the key state back to the orginal JSON content.Same is the expectation for province.
Requesting support from All...Thanks in Advance....
Below is the code i had written, but the expected result is not obtained.Can anyone help me in identifying were i have gone wrong
var testJson = JSON.parse(jsonData);
var tempFinal = [];
for(let i =0; i<testJson.length; i++) {
let itemData = {};
itemData.item = testJson[i].item;
tempFinal.push(itemData);
var state = [];
state.push( testJson[i].state);
let stateData = {};
stateData.state = state;
tempFinal.push(stateData);
var service = [];
service.push( testJson[i].service);
let serviceData = {};
serviceData.service = service;
tempFinal.push(serviceData);
}
The result obtained is
[
{
"item": {
"protocol": "tcp",
"portid": "22"
}
},
{
"state": [
{
"item": {
"state": "filtered",
"reason": "no-response",
"reason_ttl": "0"
}
}
]
},
{
"service": [
{
"item": {
"name": "ssh",
"method": "table",
"conf": "3"
}
}
]
}
]
Expected is
[
{
"item": {
"a": "a",
"a": "a"
},
"state": [
{
"item": {
"c": "b",
"e": "f",
"reason_ttl": "0"
}
}
],
"service": [
{
"item": {
"name": "q",
"method": "table",
"d": "e"
}
}
]
}
]
You can try this one
//jsonData is your original json data
jsonData.map((obj1=>{
//updating state data
obj1.state=[obj1.state];
}));
//finally print it.
console.log(jsonData);
I am trying to get the values of a key in a json file, but there are several issues that I need to solve.
The key of the JSON is dynamic - I have another JSON in which I am given the path of the key inside the JSON.
For example, I have a json file that contains the following mapping:
{
"addressesPath":"personal.addresses"
}
This tells me that the value I am looking for is inside another key, called personal.
The JSON will look like this:
{
"username": "X1",
"id":"1X",
"type": "patron",
"group": "students",
"personal": {
"lastname": "lname",
"firstname": "fname",
"email": "test#test.test",
"phone": "1-111-111-1111",
"mobilePhone": "(111)111-1111",
"birthDate": "1979-01-23T00:00:00.000+0000",
"addresses":
{
"countryId": "US",
"addressLine1": "1111 Brannon Ford Suite 111",
"city": "Kettering",
"region": "MA",
"postalCode": "11111-1111",
"primaryAddress": true
}
}
}
So for example if the JSON is "user", what I want to get is user.personal.addresses
How can I translate "user.personal.addresses" to "users.+dynamic"?
I tried doing it just like that, but it doesn't seem to work with any type of string I extract from the mapping json file.
I have an issue because I don't know if the location I am getting is a single value or an array of values.
For example, the JSON could look like this:
{
"username": "X1",
"id":"1X",
"type": "patron",
"group": "students",
"personal": {
"lastname": "lname",
"firstname": "fname",
"email": "test#test.test",
"phone": "1-111-111-1111",
"mobilePhone": "(111)111-1111",
"birthDate": "1979-01-23T00:00:00.000+0000",
"addresses":[
{
"countryId": "US",
"addressLine1": "1111 Brannon Ford Suite 111",
"city": "Kettering",
"region": "MA",
"postalCode": "11111-1111",
"primaryAddress": true
}, {
"countryId": "US",
"addressLine1": "1112 Brannon Ford Suite 112",
"city": "Kettering",
"region": "IL",
"postalCode": "11112-1112",
"primaryAddress": false
}
]
}
}
Which means I need to determine the structure of the data I am going to get, whether it is an array or not.
Can I do this by checking if the result is a string or object? I know that arrays from JSON files are read as objects in node js.
You want something like that
With three examples
let object = {
"group": "students",
"personal": {
"addresses": {
"countryId": "US",
}
}
}
let test1 = checkObject(object, "personal.addresses")
console.log(test1);
let object2 = {
"test": {
"test_deep": [
{
"countryId": "US",
"addressLine1": "1111 Brannon Ford Suite 111"
},
{
"countryId": "US",
"addressLine1": "1112 Brannon Ford Suite 112",
}
]
}
}
let test2 = checkObject(object2, "test.test_deep")
console.log(test2);
let object3 = {
"test": {
"test_deep": "test"
}
}
let test3 = checkObject(object3, "test.test_deep")
console.log(test3);
function checkObject(object, addressesPath) {
let addres = addressesPath.split(".")
let item = object
for (let index = 0; index < addres.length; index++) {
if (typeof item[addres[index]] != 'undefined') {
item = item[addres[index]]
} else {
item = null
break
}
}
return {
type: typeof item,
is_array: Array.isArray(item),
data: item
}
}
let filter = {
"metaData.transaction_id":body.transaction_id
}
let paymentInstance = await AppUserPayment.findOne(filter);
Getting null:
{
"_id": {
"$oid": "60059baeb4295aa81ce51ed0"
},
"status": true,
"_isDeleted": false,
"metaData": {
"transaction_id": 1847394
},
"createdAt": {
"$date": "2021-01-18T14:31:10.841Z"
},
"updatedAt": {
"$date": "2021-01-18T14:31:10.841Z"
},
"__v": 0
}
How to filter data from metadata (object) in MongoDB? added code and collection. How to resolve this issue.
you should convert type of body.transaction_id to number, you can like this :
let filter = {
"metaData.transaction_id": +body.transaction_id
}
let paymentInstance = await AppUserPayment.findOne(filter);
I am trying to figure out this nested ordering and nothing I do will work.
Here is a sample of the data structure I am trying to order:
{
"-KV_Lrm_93Agm8kAuXql": {
"body": {
"Acceleration": "0.0",
"Altitude": "11",
"Battery": "12.7",
"Date": "2016/09/10",
"order": 1,
"time": "2016-10-19T20:26:32Z"
}
},
"-KV_LuTfJ9VrKRHoRWuw": {
"body": {
"Acceleration": "0.0",
"Altitude": "11",
"Battery": "12.7",
"Date": "2016/09/10",
"order": 5,
"time": "2016-10-21T20:26:32Z"
}
},
"-KV_Lx9VABuEB8D3I-i1": {
"body": {
"Acceleration": "0.0",
"Altitude": "11",
"Battery": "12.7",
"Date": "2016/09/10",
"order": 2,
"time": "2016-10-01T20:26:32Z"
}
},
"-KV_LzQOM3rHEKQuwyHQ": {
"body": {
"Acceleration": "0.0",
"Altitude": "11",
"Battery": "12.7",
"Date": "2016/09/10",
"order": 10,
"time": "2016-09-01T20:26:32Z"
}
},
"-KV_M0fdznAbKanHoY91": {
"body": {
"Acceleration": "0.0",
"Altitude": "11",
"Battery": "12.7",
"Date": "2016/09/10",
"order": 6,
"time": "2016-09-20T20:26:32Z"
}
}
}
Per the firebase documentation (https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html) you can do a "deep path query". In my case, if I want to sort by order I should be able to do:
.orderByChild("body/order")
But this does nothing. It has no effect on the ordering of the results. I have tried ordering on Date and time as well and neither work. Here is my full node function. This returns the results, just not ordered:
app.get('/api/xirgo-data', function(req, res)
{
var ref = db.ref("xirgo");
ref
.orderByChild("body/order")
.on("value", function(snap) {
return res.json(snap.val());
});
});
Thanks!
When you request the value of a query in Firebase, the resulting snapshot contains the keys, values and ordering information for the matching children.
But when you then convert this to a dictionary/associative array/JavaScript object, the ordering information is lost since JavaScript objects are inherently unordered.
To ensure you can access the matching items in the correct order, use the built-in DataSnapshot.forEach() method:
var ref = db.ref("xirgo");
ref
.orderByChild("body/order")
.on("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key+': '+child.val());
});
});
Documents (pseudo, rev and id omitted):
{
"type": 1,
"username": "aron",
"data": { ... }
}
{
"type": 1,
"username": "bob",
"data": { ... }
}
{
"type": 1,
"username": "steve",
"data": { ... }
}
{
"type": 1,
"username": "steve",
"data": { ... }
}
{
"type": 2,
"username": "steve",
"data": { ... }
}
{
"type": 3,
"username": "steve",
"data": { ... }
}
{
"type": 3,
"username": "steve",
"data": { ... }
}
{
"type": 3,
"username": "steve",
"data": { ... }
}
I want to know, how many documents of type 1/2/3 steve has.
View:
count: {
map: function (doc) {
emit([doc.username, doc.type], 1);
}
reduce: function (key, values, rereduce) {
return sum(values);
}
}
Now I request
/database/_design/myDesign/_view/count?key=["steve",1] // result: 2
/database/_design/myDesign/_view/count?key=["steve",2] // result: 1
/database/_design/myDesign/_view/count?key=["steve",3] // result: 3
This works perfectly well.
To smart things up, I was wondering if I can query that in one view?
Is there a way to count the number of documents of unknown number of types in one view?
You can POST to your view with a body like this;
{"keys":[["steve",1], ["steve",2]]}
Also, try using "_sum" as your reduce function, it will run natively in Erlang and should be several times faster than doing it in Javascript.
You can perform a range query to achieve this:
.../count?startkey=["steve",1]&endkey=["steve",3]&group=true&reduce=true
This will fetch one line for every key between ["steve",1] and ["steve",3] inclusive. You can adjust values 0 and 3 according to what your types can actually be. For instance, if your types can be any scalar value, you can use ["steve",null] and ["steve",{}] as the range boundaries.