Accessing nested fields with Rethinkdb - rethinkdb

So I have a result that looks like this
"data": {
"randomkeyllasdkjflk": {
"name": "John Doe"
},
"anotherrandomkeyadf": {
"name": "Mona Lee"
}
}
and I want to access the name.
This is what I tried:
r.table('users').filter(function (doc) {
return doc('data').coerceTo('array').map(function(ref) {
return ref('name')
}).contains("John")
});
But will produce an error that says:
e: Cannot perform bracket on a non-object non-sequence
"randomkeyllasdkjflk"

use this:
r.table('users').filter(function (doc) {
return doc('data').keys().map(function(ref) {
return doc('data')(ref)('name')
}).contains("John")
});

Related

How to reformat result in graphql?

I have a query like this:
query GetProductsBySlug {
categories(
where:{slug: "pianos"}
) {
products (first: 2) {
id,
slug,
name,
price,
images(first: 1) {
url
}
}
}
}
Results from this query:
{
"data": {
"categories": [
{
"products": [
{
...
]
}
]
}
}
I want to remove "data":...", "categories":..., and only get this result:
{
"products": [
{
...
}]
}
How I can do it?
I want that result only include {"products": ...} without data and categories.
You can use just [destructuring assignment][1] and get just the categories like
const {data:{categories}} = queryResult;
and then map this categories array like
categories.map(category=> category.products)
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Spring Boot Mongo update nested array of documents

I'm trying to set an attribute of a document inside an array to uppercase.
This is a document example
{
"_id": ObjectId("5e786a078bc3b3333627341e"),
"test": [
{
"itemName": "alpha305102992",
"itemNumber": ""
},
{
"itemName": "beta305102630",
"itemNumber": "P5000"
},
{
"itemName": "gamma305102633 ",
"itemNumber": ""
}]
}
I already tried a lot of thing.
private void NameElementsToUpper() {
AggregationUpdate update = AggregationUpdate.update();
//This one does not work
update.set("test.itemName").toValue(StringOperators.valueOf(test.itemName).toUpper());
//This one also
update.set(SetOperation.set("test.$[].itemName").withValueOfExpression("test.#this.itemName"));
//And every variant in between these two.
// ...
Query query = new Query();
UpdateResult result = mongoTemplate.updateMulti(query, update, aClass.class);
log.info("updated {} records", result.getModifiedCount());
}
I see that Fields class in spring data is hooking into the "$" char and behaving special if you mention it. Do not seem to find the correct documentation.
EDIT: Following update seems to work but I do not seem to get it translated into spring-batch-mongo code
db.collection.update({},
[
{
$set: {
"test": {
$map: {
input: "$test",
in: {
$mergeObjects: [
"$$this",
{
itemName: {
$toUpper: "$$this.itemName"
}
}
]
}
}
}
}
}
])
Any solutions?
Thanks!
For now I'm using which does what i need. But a spring data way would be cleaner.
mongoTemplate.getDb().getCollection(mongoTemplate.getCollectionName(Application.class)).updateMany(
new BasicDBObject(),
Collections.singletonList(BasicDBObject.parse("""
{
$set: {
"test": {
$map: {
input: "$test",
in: {
$mergeObjects: [
"$$this",
{
itemName: { $toUpper: "$$this.itemName" }
}
]
}
}
}
}
}
"""))
);

Unknown Type of Strapi/Gatsby Graphql Query Fragment

I'm trying to query data within a Strapi Dynamic Zone in Gatsby. In the Graphql Playground I can get this to work, but using the same query in Gatsby I receive the following error in the terminal:
error Unknown type "ComponentTextArticleCopy" graphql/template-strings
And my query in article.js
export const query = graphql`
query ArticleTemplate($id: String!) {
strapiArticle(id: { eq: $id }) {
articleHeader {
articleTitle
articleSnippet
}
articleContent {
__typename
... on ComponentTextArticleCopy {
contentCopy
}
... on ComponentImageContentImg {
imgCaption
}
... on ComponentTextArticleQuote {
contentQuote
}
}
}
}
`
According to the Graphql docs, Inline Fragment would seem to be the right approach but clearly I've got something wrong somewhere.
The following query 'works' on Gatsby but tries to resolve for all components:
query MyQuery {
allStrapiArticle {
edges {
node {
__typename
articleContent {
contentCopy
contentQuote
}
}
}
}
}
{
"data": {
"allStrapiArticle": {
"edges": [
{
"node": {
"__typename": "StrapiArticle",
"articleContent": [
{
"contentCopy": null,
"contentQuote": null
},
{
"contentCopy": "What a great city Gothenburg is. We even took a trip out to the archipelago. ",
"contentQuote": null
},
{
"contentCopy": null,
"contentQuote": null
},
{
"contentCopy": null,
"contentQuote": "You must visit at have fika"
}
]
}
}
]
}
},
Deleting Cache folder and running again worked for me.

Conversion from nested objects to hierarchical data structure in d3.js

I want to convert the following nested object into hierarchical data structure
{
"AP":{
"districts":{
"Anantapur":{
"total":{
"confirmed":66593,
"deceased":587,
"recovered":65697
}
},
"Chittoor":{
...
}
}
},
"AR":{
"districts":{....}
}...so on
}
to
[
{
"name":"AP",
"children":[
{
"name":"Anantapur",
"children":[
{
"name":"confirmed",
"value":66593
},
{
"name":"deceased",
"value":587
},
{
"name":"recovered",
"value":65697
}
]
},
{
...
}
]
},...so on
]
How can this be done?...I tried using d3 nest but there is no common key value like
"state":"AP", "state":"AR".
Here "AP" and "AR" are keys themselves. Is there any other method of doing this?
You can use Object.keys(data).map(function(key) { to create an array with an item for every property in your objects. You can nest this approach to get to the desired outcome. Here's a manual solution for your data structure (you could use a recursive function for arbitrarily nested data with a slightly different output, but given the depth of the object and the structure of the output, I have not done that):
var data = { "State One":{
"districts":{
"Region A":{
"total":{
"confirmed":1,
"deceased":2,
"recovered":3
}
},
"Region B":{
"total":{
"confirmed":4,
"deceased":5,
"recovered":6
}
}
}
},
"State Two":{
"districts":{
"Region C":{
"total":{
"confirmed":7,
"deceased":8,
"recovered":9
}
}
}
}
}
var output = Object.keys(data).map(function(key) {
return {
name:key,
children: Object.keys(data[key]["districts"]).map(function(district) {
return {
name:district,
children: Object.keys(data[key]["districts"][district]["total"]).map(function(d) {
return { name: d, value:data[key]["districts"][district]["total"][d] }
})
}
})
}
})
console.log(output);

GraphQL Mutation with JSON Patch

Are there any data types in GraphQL that can be used to describe a JSON Patch operation?
The structure of a JSON Patch operation is as follows.
{ "op": "add|replace|remove", "path": "/hello", "value": ["world"] }
Where value can be any valid JSON literal or object, such as.
"value": { "name": "michael" }
"value": "hello, world"
"value": 42
"value": ["a", "b", "c"]
op and path are always simple strings, value can be anything.
If you need to return JSON type then graphql have scalar JSON
which return any JSON type where you want to return it.
Here is schema
`
scalar JSON
type Response {
status: Boolean
message: String
data: JSON
}
type Test {
value: JSON
}
type Query {
getTest: Test
}
type Mutation {
//If you want to mutation then pass data as `JSON.stringify` or json formate
updateTest(value: JSON): Response
}
`
In resolver you can return anything in json format with key name "value"
//Query resolver
getTest: async (_, {}, { context }) => {
// return { "value": "hello, world" }
// return { "value": 42 }
// return { "value": ["a", "b", "c"] }
// return anything in json or string
return { "value": { "name": "michael" } }
},
// Mutation resolver
async updateTest(_, { value }, { }) {
// Pass data in JSON.stringify
// value : "\"hello, world\""
// value : "132456"
// value : "[\"a\", \"b\", \"c\"]"
// value : "{ \"name\": \"michael\" }"
console.log( JSON.parse(value) )
//JSON.parse return formated required data
return { status: true,
message: 'Test updated successfully!',
data: JSON.parse(value)
}
},
the only thing you need to specifically return "value" key to identify to get in query and mutation
Query
{
getTest {
value
}
}
// Which return
{
"data": {
"getTest": {
"value": {
"name": "michael"
}
}
}
}
Mutation
mutation {
updateTest(value: "{ \"name\": \"michael\" }") {
data
status
message
}
}
// Which return
{
"data": {
"updateTest": {
"data": null,
"status": true,
"message": "success"
}
}
}

Resources