How to create nested object in MongoDB schema, nested object and array MEAN stack - json

I'm trying to design a nested MongoDB schema.
Currently, I have this schema and it's working:
var CompanySchema = new mongoose.Schema({
name: String,
rate: number
date: Date
})
But I wanna expend it to get:
var CompanySchema = new mongoose.Schema({
name: String,
currency: {
mxn: Number,
php: Number,
},
source: [String],
deliveryMethod: [String],
date: Date
})
For source, I want to get an array of inputs ex. ["bank", "debit card", "agent"]
and almost samething for deliverymethod.
But either my input is wrong or my schema, because the value for source saves as one long string, not a separated value.
Also, I think the way I designed the currency to have more currency rate is correct but I don't know how my input json should suppose to be.
I tried it in postman:
{
"name": "google",
"currency": {
"mxn": 20,
"php": 30
}
}
and this is the result i got:
{
"status": 201,
"data": {
"__v": 0,
"name": "google",
"date": "2017-12-06T22:38:45.896Z",
"_id": "5a2871752e3b7343dc388549",
"deliveryMethod": [
null
],
"source": [
null
]
},
"message": "Succesfully Created Company"
}
1- if my currency nested schema is correct how should be my post json file be?
2- how can I get source and deliveryMethod as an array of string?

The JSON in the request body should look like this:
{
"name": "google",
"currency": {
"mxn": 20,
"php": 30
},
"source": ["source1", "source 2", "source 3"],
"deliveryMethod": ["delMetd 1", "delMetd 2", "delMetd 3"],
"date": "2015-11-27T23:00:00Z"
}
I copy/pasted your code and tried with Postman. The response I got back was:
{
"__v": 0,
"name": "google",
"date": "2015-11-27T23:00:00.000Z",
"_id": "5a2915295c5f714f7cb25d90",
"deliveryMethod": [
"delMetd 1",
"delMetd 2",
"delMetd 3"
],
"source": [
"source1",
"source 2",
"source 3"
],
"currency": {
"mxn": 20,
"php": 30
}
}
If I connect to the database with the mongo shell and run db.companies.find().pretty() I get this result:
{
"_id" : ObjectId("5a2915295c5f714f7cb25d90"),
"name" : "google",
"date" : ISODate("2015-11-27T23:00:00Z"),
"deliveryMethod" : [
"delMetd 1",
"delMetd 2",
"delMetd 3"
],
"source" : [
"source1",
"source 2",
"source 3"
],
"currency" : {
"mxn" : 20,
"php" : 30
},
"__v" : 0
}
Your schema is fine. You can try dropping the collection (db.companies.drop()) if you can't get it to work. Start with a fresh one if you don't have any important data in it.

Related

How to save data in Json format in React-admin v3?

I created JsonInput, which sends a json object to the input SimpleForm, however, a modified version of it gets into the Data Provider.
that's what is sent to the input:
json: {
"FunctionalGroup": [
{
"uaIDref": [
"2104"
],
"_Name": "Текущие параметры",
"_ID": "33"
},
{
"uaIDref": [
"2100"
],
"_Name": "Текущие параметры пониженной точности",
"_ID": "34"
},
],
"_Name": "Прибор 1",
"_ID": "32"
}
that's what came to the server:
json: {
"FunctionalGroup": [
{
"uaIDref": [
"2104"
],
"_Name": "Текущие параметры",
"_ID": "33"
},
{
"uaIDref": [
"2100"
],
"_Name": "Текущие параметры пониженной точности",
"_ID": "34"
}
],
"FunctionalGroupIds": "",
"_Name": "Прибор 1",
"_ID": "32"
},
after a response from the server with this object, this is what came in the field:
json: {
FunctionalGroup: [
{
uaIDref: [
'2104'
]
},
{
uaIDref: [
'2100'
]
}
],
FunctionalGroupIds: ''
}
what kind of magic is this?
I did some tests. When I converted the object to a string, the correct json was sent to the server, however, in the field after the server responded, the modified object was displayed again.
I found out that the conversion is related to redux.js, but what exactly happens is not understood.
Please give any comments on this.
How can I make save json?

converted json result structure not same as source

i have test case to compare against the source kept in Kafka message.
I noticed the structured is not same.
no missing field, but the structure is not arranged in the same sequence.
how do i make the result converted same as the source structure?
code to retrieve the message, then decode the base64 format and prettyprint the result.
def responseList = new JsonSlurper().parseText(consumeMessage.getResponseText())
println('response text: \n' + JsonOutput.prettyPrint(JsonOutput.toJson(responseList)))
def decoded = new JsonSlurper().parseText(new String(responseList[0].value.decodeBase64()))
println('response decoded text: \n' + JsonOutput.prettyPrint(JsonOutput.toJson(decoded)))
below is the result printed at console
2019-11-20 16:36:44.934 DEBUG oingDRToAllocationVerification-DynamicID - 10: decoded = JsonSlurper().parseText(new java.lang.String(responseList[0].value.decodeBase64()))
2019-11-20 16:36:44.945 DEBUG oingDRToAllocationVerification-DynamicID - 11: println("response decoded text:
" + JsonOutput.prettyPrint(JsonOutput.toJson(decoded)))
response decoded text:
{
"contexts": [
{
"activityId": "c2884e63-d30d-48a3-965c-0b33202885c2",
"incomingTimestamp": "2019-11-20T08:36:29.0829958Z",
"sourceName": "DispenseOrderService",
"timestamp": "2019-11-20T08:36:29.0829958+00:00",
"userId": "unknown"
}
],
"dispenseOrder": [
{
"dispenseRequestType": "DISPENSEORDER",
"id": "6320112019043628",
"items": [
{
"administrationInstructions": "drug intake information test 123",
"dispenseAsWritten": false,
"id": "cda92ec7-3191-4b7b-a972-7f4545146db4",
"itemId": "Augmentn",
"quantity": 100
},
{
"administrationInstructions": "drug intake information test 234",
"dispenseAsWritten": false,
"id": "19e00776-b08d-47c8-930b-76ddc01f0ff4",
"itemId": "Clopidogrl",
"quantity": 200
},
{
"administrationInstructions": "drug intake information test 456",
"dispenseAsWritten": true,
"id": "0a5b0f4a-366d-4fa7-a0b8-2e8c83f4af13",
"itemId": "Adenosine",
"quantity": 300
}
],
"locationId": "Pharmacy Jewel East",
"piiIdentifiers": {
"doctorId": "b502f046-fb1e-4fcf-8135-a7a13cfb47f6",
"patientId": "fe49b461-8eeb-46d5-b995-a31cdaaa35f3",
"pharmacistId": "b502f046-fb1e-4fcf-8135-a7a13cfb47f6"
},
"priority": 4,
"state": "NEW",
"type": "Test ingest type"
}
],
"messageClass": "DispenseRequestV1",
"messageId": "83e94dac-dfb6-49d7-8ca0-219d155fecce",
"notifications": [
],
"operation": "Add",
"timestamp": "2019-11-20T08:36:29.0952632+00:00"
}
below is the source. the result after conversion is not same as source. as in the structure is not arranged accordingly.
{
"operation" : "Add",
"dispenseOrder" : [ {
"id" : "6320112019043628",
"locationId" : "Pharmacy Jewel East",
"piiIdentifiers" : {
"patientId" : "fe49b461-8eeb-46d5-b995-a31cdaaa35f3",
"doctorId" : "b502f046-fb1e-4fcf-8135-a7a13cfb47f6",
"pharmacistId" : "b502f046-fb1e-4fcf-8135-a7a13cfb47f6"
},
"priority" : 4,
"state" : "NEW",
"type" : "Test ingest type",
"dispenseRequestType" : "DISPENSEORDER",
"items" : [ {
"id" : "cda92ec7-3191-4b7b-a972-7f4545146db4",
"itemId" : "Augmentn",
"quantity" : 100,
"dispenseAsWritten" : false,
"administrationInstructions" : "drug intake information test 123"
}, {
"id" : "19e00776-b08d-47c8-930b-76ddc01f0ff4",
"itemId" : "Clopidogrl",
"quantity" : 200,
"dispenseAsWritten" : false,
"administrationInstructions" : "drug intake information test 234"
}, {
"id" : "0a5b0f4a-366d-4fa7-a0b8-2e8c83f4af13",
"itemId" : "Adenosine",
"quantity" : 300,
"dispenseAsWritten" : true,
"administrationInstructions" : "drug intake information test 456"
} ]
} ],
"messageId" : "83e94dac-dfb6-49d7-8ca0-219d155fecce",
"timestamp" : "2019-11-20T08:36:29.0952632+00:00",
"messageClass" : "DispenseRequestV1",
"contexts" : [ {
"userId" : "unknown",
"timestamp" : "2019-11-20T08:36:29.0829958+00:00",
"activityId" : "c2884e63-d30d-48a3-965c-0b33202885c2",
"incomingTimestamp" : "2019-11-20T08:36:29.0829958Z",
"sourceName" : "DispenseOrderService"
} ],
"notifications" : [ ]
}
As json.org says:
An object is an unordered set of name/value pairs.
So, different JSON methods/libraries might order them in a different way. You shouldn't rely on order of name/value pairs when working with JSON.
(If order is very important to you, you might try using suggested solution from this post.)

How to combine columns in spark as a JSON in Scala

I have a variable which is constructed as follows extracting data using Spark SQL:
{
"resourceType" : "Test1",
"count" : 10,
"entry": [{
"id": "112",
"gender": "female",
"birthDate": 1213999
}, {
"id": "urn:uuid:002e27cf-3cae-4393-89c5-1b78050d9428",
"resourceType": "Encounter"
}]
}
I want the output in the following format:
{
"resourceType" : "Test1",
"count" : 10,
"entry" :[
"resource" :{
"id": "112",
"gender": "female",
"birthDate": 1213999
},
"resource" :{
"id": "urn:uuid:002e27cf-3cae-4393-89c5-1b78050d9428",
"resourceType": "Encounter"
}]
}
I am basically new to Scala :), would need help in this.
EDIT: Adding the scala code to create the JSON:
val bundle = endresult.groupBy("id").agg(count("*") as "total",collect_list("resource") as "entry").
withColumn("resourceType", lit("Bundle")).
drop("id").
select(to_json(struct("resourceType","entry"))).
map(row => row.getString(0).
replace("\"entry\":[\"{", "\"entry\":[{").
replace("}\"]}","}]}"). // Should be at the end of the string ONLY (we might switch to regex instead
replace("}\",\"{","},{")
replace("\\\"", "\"")
)

New line feed in json data

I'm having a json file as :-
{
VALUES: [
{
"UTAGID": "SYSTEM_CHILLER1",
"tagName": "P1",
"tagValue": "10",
"tagTime": "2015-07-23T14:29:30.731Z",
"tagQuality": "128"
},
{
"UTAGID": "SYSTEM_CHILLER1",
"tagName": "P1",
"tagValue": "10",
"tagTime": "2015-07-23T14:29:30.731Z",
"tagQuality": "128"
},
{
"UTAGID": "SYSTEM_CHILLER1",
"tagName": "P1",
"tagValue": "10",
"tagTime": "2015-07-23T14:29:30.731Z",
"tagQuality": "128"
}
]
};
where each record is not on a single line.I'm able to retrieve values from a hive table based on this if each record appears on a single line else it shows null values.
What could be the reason?how do I insert new line feed after each record?
Thanks

Elasticsearch - completion suggester payload transforming, returns invalid JSON

I am trying to use the elasticsearch completion suggester. I have app_user objects, which come into my elasticsearch instance via a couchdb river.
This is the mapping I use:
{
"app_user" : {
"_all" : {"enabled" : true},
"_source" : {
"includes" : [
"_id",
"_rev",
"type",
"profile.callname",
"profile.fullname",
"email"
]
},
"properties" : {
"suggest" : { "type" : "completion",
"index_analyzer" : "simple",
"search_analyzer" : "simple",
"payloads" : true
}
},
"transform" : [
{"script": "ctx._source.suggest = ['input':[ctx._source.email, ctx._source.profile.fullname, ctx._source.profile.callname]]"},
{"script": "ctx._source.suggest.payload = ['_id': ctx._source['_id'], 'type': ctx._source['type'], '_rev': ctx._source['_rev']]"}
,
{"script": "ctx._source.suggest.payload << ['label': ctx._source.profile.fullname, 'text': ctx._source.email]"}
]
}
}
So I am trying to include the object ID and a display text in the payload.
When I view the generated document via http://localhost:9200/myindex/app_user/<someid>?pretty&_source_transform, everything seems OK:
{
"_index": "myindex",
"_type": "app_user",
"_id": "<someid>",
"found": true,
"_source": {
"_rev": "2-dcd7b9d456e205d3e9d859fdc2c6a688",
"_id": "<someid>",
"email": "joni#example.org",
"suggest": {
"input": [
"joni#example.org",
...
],
"output": "joni surname - joni#example.org",
"payload": {
"_id": "<someid>",
"type": "app_user",
"_rev": "2-dcd7b9d456e205d3e9d859fdc2c6a688",
"label": "joni surname",
"text": "joni#example.org"
}
},
"type": "app_user",
"profile": {
"callname": "",
"fullname": "joni surname"
}
}
}
However, when I try to get the document via _suggest, elasticsearch API somehow breaks the JSON object payload:
curl -XGET "http://localhost:9200/myindex/_suggest" -d '{
"all-suggest": {
"text": "joni",
"completion": {
"field": "suggest"
}
}
}'
results in
{"_shards":{"total":5,"successful":5,"failed":0},"all-suggest":[{"text":"joni","offset":0,"length":5,"options":[{"text":"joni surname - joni#example.org","score":1.0,"payload"::)
�_id`<someid>�typeIapp_user�_reva2-dcd7b9d456e205d3e9d859fdc2c6a688�label�joni surname�textSjoni#example.org�}]}]}
which is definitely no valid JSON.. Any ideas?
This is actually a bug in elasticsearch. It was reported and acknowledged here and should be fixed shortly.