Well I need help! I am trying to access a specific properties from a complex JSON array object in React.js. Here is the complete JSON where I need to grab some properties from.
{
"resultsPerPage": 7,
"startIndex": 0,
"totalResults": 7,
"result": {
"CVE_data_type": "CVE",
"CVE_data_format": "MITRE",
"CVE_data_version": "4.0",
"CVE_data_timestamp": "2021-12-15T08:44Z",
"CVE_Items": [
{
"cve": {
"data_type": "CVE",
"data_format": "MITRE",
"data_version": "4.0",
"CVE_data_meta": {
"ID": "CVE-2007-5532",
"ASSIGNER": "cve#mitre.org"
},
"problemtype": {
"problemtype_data": [
{
"description": [
{
"lang": "en",
"value": "NVD-CWE-noinfo"
}
]
}
]
},
"references": {
"reference_data": [
{
"url": "http://www.securitytracker.com/id?1018823",
"name": "1018823",
"refsource": "SECTRACK",
"tags": [
"Third Party Advisory",
"VDB Entry"
]
},
{
"url": "http://secunia.com/advisories/27251",
"name": "27251",
"refsource": "SECUNIA",
"tags": [
"Third Party Advisory"
]
},
{
"url": "http://www.us-cert.gov/cas/techalerts/TA07-290A.html",
"name": "TA07-290A",
"refsource": "CERT",
"tags": [
"Third Party Advisory",
"US Government Resource"
]
},
{
"url": "http://secunia.com/advisories/27409",
"name": "27409",
"refsource": "SECUNIA",
"tags": [
"Third Party Advisory"
]
},
{
"url": "http://www.vupen.com/english/advisories/2007/3524",
"name": "ADV-2007-3524",
"refsource": "VUPEN",
"tags": [
"Permissions Required"
]
},
{
"url": "http://www.vupen.com/english/advisories/2007/3626",
"name": "ADV-2007-3626",
"refsource": "VUPEN",
"tags": [
"Permissions Required"
]
},
{
"url": "http://marc.info/?l=bugtraq&m=119332677525918&w=2",
"name": "SSRT061201",
"refsource": "HP",
"tags": [
"Mailing List",
"Third Party Advisory"
]
},
{
"url": "http://www.oracle.com/technetwork/topics/security/cpuoct2007-092913.html",
"name": "http://www.oracle.com/technetwork/topics/security/cpuoct2007-092913.html",
"refsource": "CONFIRM",
"tags": [
"Vendor Advisory"
]
}
]
},
"description": {
"description_data": [
{
"lang": "en",
"value": "Unspecified vulnerability in the People Tools component in Oracle PeopleSoft Enterprise and JD Edwards EnterpriseOne 8.22.17, 8.47.14, 8.48.13, 8.49.05 has unknown impact and remote attack vectors, aka PSE01."
}
]
}
},
"configurations": {
"CVE_data_version": "4.0",
"nodes": [
{
"operator": "OR",
"children": [],
"cpe_match": [
{
"vulnerable": true,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:*:*:*:*:*:*:*:*",
"versionStartIncluding": "8.47",
"versionEndIncluding": "8.47.14",
"cpe_name": []
},
{
"vulnerable": true,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:*:*:*:*:*:*:*:*",
"versionStartIncluding": "8.49",
"versionEndIncluding": "8.49.05",
"cpe_name": []
},
{
"vulnerable": true,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:*:*:*:*:*:*:*:*",
"versionStartIncluding": "8.22",
"versionEndIncluding": "8.22.17",
"cpe_name": []
},
{
"vulnerable": true,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:*:*:*:*:*:*:*:*",
"versionStartIncluding": "8.48",
"versionEndIncluding": "8.48.13",
"cpe_name": []
}
]
}
]
},
"impact": {
"baseMetricV2": {
"cvssV2": {
"version": "2.0",
"vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P",
"accessVector": "NETWORK",
"accessComplexity": "LOW",
"authentication": "NONE",
"confidentialityImpact": "PARTIAL",
"integrityImpact": "PARTIAL",
"availabilityImpact": "PARTIAL",
"baseScore": 7.5
},
"severity": "HIGH",
"exploitabilityScore": 10,
"impactScore": 6.4,
"obtainAllPrivilege": false,
"obtainUserPrivilege": false,
"obtainOtherPrivilege": false,
"userInteractionRequired": false
}
},
"publishedDate": "2007-10-17T23:17Z",
"lastModifiedDate": "2019-10-09T22:54Z"
},
{
"cve": {
"data_type": "CVE",
"data_format": "MITRE",
"data_version": "4.0",
"CVE_data_meta": {
"ID": "CVE-2007-2131",
"ASSIGNER": "cve#mitre.org"
},
"problemtype": {
"problemtype_data": [
{
"description": [
{
"lang": "en",
"value": "NVD-CWE-Other"
}
]
}
]
},
"references": {
"reference_data": [
{
"url": "http://www.red-database-security.com/advisory/oracle_cpu_apr_2007.html",
"name": "http://www.red-database-security.com/advisory/oracle_cpu_apr_2007.html",
"refsource": "MISC",
"tags": []
},
{
"url": "http://www.securitytracker.com/id?1017927",
"name": "1017927",
"refsource": "SECTRACK",
"tags": []
},
{
"url": "http://www.us-cert.gov/cas/techalerts/TA07-108A.html",
"name": "TA07-108A",
"refsource": "CERT",
"tags": [
"US Government Resource"
]
},
{
"url": "http://www.securityfocus.com/bid/23532",
"name": "23532",
"refsource": "BID",
"tags": []
},
{
"url": "http://www.vupen.com/english/advisories/2007/1426",
"name": "ADV-2007-1426",
"refsource": "VUPEN",
"tags": []
},
{
"url": "http://www.oracle.com/technetwork/topics/security/cpuapr2007-090632.html",
"name": "http://www.oracle.com/technetwork/topics/security/cpuapr2007-090632.html",
"refsource": "CONFIRM",
"tags": []
},
{
"url": "http://www.securityfocus.com/archive/1/466329/100/200/threaded",
"name": "SSRT061201",
"refsource": "HP",
"tags": []
}
]
},
"description": {
"description_data": [
{
"lang": "en",
"value": "Unspecified vulnerability in PeopleTools in Oracle PeopleSoft Enterprise 8.22.14, 8.47.12, and 8.48.08 has unknown impact and attack vectors, aka PSE01."
}
]
}
},
"configurations": {
"CVE_data_version": "4.0",
"nodes": [
{
"operator": "OR",
"children": [],
"cpe_match": [
{
"vulnerable": true,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:8.22.14:*:*:*:*:*:*:*",
"cpe_name": []
},
{
"vulnerable": true,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:8.47.12:*:*:*:*:*:*:*",
"cpe_name": []
},
{
"vulnerable": true,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:8.48.08:*:*:*:*:*:*:*",
"cpe_name": []
}
]
}
]
},
"impact": {
"baseMetricV2": {
"cvssV2": {
"version": "2.0",
"vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C",
"accessVector": "NETWORK",
"accessComplexity": "LOW",
"authentication": "NONE",
"confidentialityImpact": "COMPLETE",
"integrityImpact": "COMPLETE",
"availabilityImpact": "COMPLETE",
"baseScore": 10
},
"severity": "HIGH",
"exploitabilityScore": 10,
"impactScore": 10,
"obtainAllPrivilege": false,
"obtainUserPrivilege": false,
"obtainOtherPrivilege": false,
"userInteractionRequired": false
}
},
"publishedDate": "2007-04-18T18:19Z",
"lastModifiedDate": "2018-10-16T16:42Z"
},
{
"cve": {
"data_type": "CVE",
"data_format": "MITRE",
"data_version": "4.0",
"CVE_data_meta": {
"ID": "CVE-2005-3463",
"ASSIGNER": "cve#mitre.org"
},
"problemtype": {
"problemtype_data": [
{
"description": [
{
"lang": "en",
"value": "NVD-CWE-noinfo"
}
]
}
]
},
"references": {
"reference_data": [
{
"url": "http://www.us-cert.gov/cas/techalerts/TA05-292A.html",
"name": "TA05-292A",
"refsource": "CERT",
"tags": [
"US Government Resource"
]
},
{
"url": "http://www.kb.cert.org/vuls/id/210524",
"name": "VU#210524",
"refsource": "CERT-VN",
"tags": [
"US Government Resource"
]
},
{
"url": "http://www.securityfocus.com/bid/15134",
"name": "15134",
"refsource": "BID",
"tags": []
},
{
"url": "http://secunia.com/advisories/17250",
"name": "17250",
"refsource": "SECUNIA",
"tags": []
},
{
"url": "http://www.oracle.com/technetwork/topics/security/cpuoct2005-090497.html",
"name": "http://www.oracle.com/technetwork/topics/security/cpuoct2005-090497.html",
"refsource": "CONFIRM",
"tags": []
}
]
},
"description": {
"description_data": [
{
"lang": "en",
"value": "Unspecified vulnerability in PeopleTools in Oracle PeopleSoft Enterprise 8.44 up to 8.46.03 has unknown impact and attack vectors, as identified by Oracle Vuln# PSE03."
}
]
}
},
"configurations": {
"CVE_data_version": "4.0",
"nodes": [
{
"operator": "OR",
"children": [],
"cpe_match": [
{
"vulnerable": true,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:8.44:*:*:*:*:*:*:*",
"cpe_name": []
},
{
"vulnerable": true,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:*:*:*:*:*:*:*:*",
"versionEndIncluding": "8.46.03",
"cpe_name": []
}
]
}
]
},
"impact": {
"baseMetricV2": {
"cvssV2": {
"version": "2.0",
"vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C",
"accessVector": "NETWORK",
"accessComplexity": "LOW",
"authentication": "NONE",
"confidentialityImpact": "COMPLETE",
"integrityImpact": "COMPLETE",
"availabilityImpact": "COMPLETE",
"baseScore": 10
},
"severity": "HIGH",
"exploitabilityScore": 10,
"impactScore": 10,
"obtainAllPrivilege": false,
"obtainUserPrivilege": false,
"obtainOtherPrivilege": false,
"userInteractionRequired": false
}
},
"publishedDate": "2005-11-02T11:03Z",
"lastModifiedDate": "2016-05-11T18:14Z"
},
{
"cve": {
"data_type": "CVE",
"data_format": "MITRE",
"data_version": "4.0",
"CVE_data_meta": {
"ID": "CVE-2005-3461",
"ASSIGNER": "cve#mitre.org"
},
"problemtype": {
"problemtype_data": [
{
"description": [
{
"lang": "en",
"value": "NVD-CWE-Other"
}
]
}
]
},
"references": {
"reference_data": [
{
"url": "http://www.us-cert.gov/cas/techalerts/TA05-292A.html",
"name": "TA05-292A",
"refsource": "CERT",
"tags": [
"US Government Resource"
]
},
{
"url": "http://www.kb.cert.org/vuls/id/210524",
"name": "VU#210524",
"refsource": "CERT-VN",
"tags": [
"US Government Resource"
]
},
{
"url": "http://www.securityfocus.com/bid/15134",
"name": "15134",
"refsource": "BID",
"tags": []
},
{
"url": "http://secunia.com/advisories/17250",
"name": "17250",
"refsource": "SECUNIA",
"tags": []
},
{
"url": "http://www.oracle.com/technetwork/topics/security/cpuoct2005-090497.html",
"name": "http://www.oracle.com/technetwork/topics/security/cpuoct2005-090497.html",
"refsource": "CONFIRM",
"tags": []
}
]
},
"description": {
"description_data": [
{
"lang": "en",
"value": "Unspecified vulnerability in PeopleTools in Oracle PeopleSoft Enterprise 8.42 up to 8.45.17 has unknown impact and attack vectors, as identified by Oracle Vuln# PSE01."
}
]
}
},
"configurations": {
"CVE_data_version": "4.0",
"nodes": [
{
"operator": "OR",
"children": [],
"cpe_match": [
{
"vulnerable": false,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:8.1:*:*:*:*:*:*:*",
"cpe_name": []
},
{
"vulnerable": false,
"cpe23Uri": "cpe:2.3:a:oracle:peoplesoft_enterprise:*:*:*:*:*:*:*:*",
"versionEndIncluding": "8.45.17",
"cpe_name": []
}
]
}
]
},
"impact": {
"baseMetricV2": {
"cvssV2": {
"version": "2.0",
"vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C",
"accessVector": "NETWORK",
"accessComplexity": "LOW",
"authentication": "NONE",
"confidentialityImpact": "COMPLETE",
"integrityImpact": "COMPLETE",
"availabilityImpact": "COMPLETE",
"baseScore": 10
},
"severity": "HIGH",
"exploitabilityScore": 10,
"impactScore": 10,
"obtainAllPrivilege": false,
"obtainUserPrivilege": false,
"obtainOtherPrivilege": false,
"userInteractionRequired": false
}
},
"publishedDate": "2005-11-02T11:03Z",
"lastModifiedDate": "2016-04-30T01:59Z"
},
{
"cve": {
"data_type": "CVE",
"data_format": "MITRE",
"data_version": "4.0",
"CVE_data_meta": {
"ID": "CVE-2007-5534",
"ASSIGNER": "cve#mitre.org"
},
"problemtype": {
"problemtype_data": [
{
"description": [
{
"lang": "en",
"value": "NVD-CWE-noinfo"
}
]
}
]
},
]
}
]
},
}
]
}
}
The properties I wanted to fetch are ID from CVE_data_meta{}, value from description_data{} and exploitabilityScore, severity and impactScore from impact{}
Here is my react component where i wanted to render this properties
import React, { useState, useEffect } from "react";
import HelpOutlineIcon from "#mui/icons-material/HelpOutline";
import axios from "axios";
const VendorsDetail = () => {
const [data, setData] = useState({});
const baseURL =
"http://127.0.0.1:8000/api/business_process/business-impact/vendor-product-detail";
useEffect(() => {
axios
.get(baseURL)
.then((response) => {
setData(response.data);
})
.then(
(response) => {},
(err) => {
alert("No Data To Show");
}
)
.catch((err) => {
return false;
});
}, []);
const DisplayData = data.result.CVE_Items.cve.CVE_data_meta?.map((vendor) => {
return (
<tr>
<td>{vendor.ID}</td>
</tr>
);
});
return (
<div className="z-100">
<div className="text-black">
<div className="rounded overflow-hidden flex justify-center items-center">
<table class="table table-striped ">
<thead>
<tr>
<th>ID</th>
<th>DESCRIPTION DATA</th>
<th>value</th>
<th>exploitabilityScore</th>
<th>severity</th>
<th>impactScore</th>
</tr>
</thead>
<tbody>{DisplayData}</tbody>
</table>
</div>
<h1>{foo}</h1>
</div>
</div>
);
};
export default VendorsDetail;
import React, { useState, useEffect } from "react";
import HelpOutlineIcon from "#mui/icons-material/HelpOutline";
import axios from "axios";
const VendorsDetail = () => {
const [data, setData] = useState({});
const baseURL =
"http://127.0.0.1:8000/api/business_process/business-impact/vendor-product-detail";
useEffect(() => {
axios
.get(baseURL)
.then((response) => {
setData(response.data);
})
.then(
(response) => {},
(err) => {
alert("No Data To Show");
}
)
.catch((err) => {
return false;
});
}, []);
?
const DisplayData = data?.result?.CVE_Items.map((vender) => {
return (
<tr>
<td>{vendor?.cve?.CVE_data_meta?.ID}</td>
<td>{vendor?.cve?.description?.description_data?.[0]?.lang}</td>
<td>{vendor?.cve?.impact?.exploitabilityScore}</td>
<td>{vendor?.cve?.impact?.severity}</td>
<td>{vendor?.cve?.impact?.impactScore}</td>
</tr>
);
});
return (
<div className="z-100">
<div className="text-black">
<div className="rounded overflow-hidden flex justify-center items-center">
<table class="table table-striped ">
<thead>
<tr>
<th>ID</th>
<th>DESCRIPTION DATA</th>
<th>value</th>
<th>exploitabilityScore</th>
<th>severity</th>
<th>impactScore</th>
</tr>
</thead>
<tbody>{DisplayData}</tbody>
</table>
</div>
<h1>{foo}</h1>
</div>
</div>
);
};
export default VendorsDetail;
You need to JSON.parse(data) before being able to access the properties.
useEffect(() => {
axios
.get(baseURL)
.then((response) => {
setData(JSON.parse(response.data));
})
You probably want to change the data you get back from your api or that you are reading from a file into a more useable format for what you are trying to do.
The data structure you are receiving is roughly -
{
"resultsPerPage":7,
"startIndex":0,
"totalResults":7,
"result": [
"CVE_data_type":"CVE",
"CVE_data_format":"MITRE",
"CVE_data_version":"4.0",
"CVE_data_timestamp":"2021-12-15T08:44Z",
"CVE_Items": [
{
"cve": {
"CVE_data_meta": { ID: "THE ID YOU WANT" },
"description": {
"description_data": [{ "lang" : "en", "value": "problem desc"}],
},
},
"impact": {
"baseMetricV2": {
"cvssv2": {
"severity":"HIGH",
"exploitabilityScore":10,
"impactScore":6.4,
}
}
}
},
]
]
}
Since you only need some of these fields, you can reduce the extra data you have to deal with by destructuring off the needed fields -
const DisplayData = data?.result?.CVE_Items.map(({
cve: {
CVE_data_meta: { ID },
description: { description_data },
},
impact: {
baseMetricV2: {
cvssv2: {
severity,
exploitabilityScore,
impactScore,
}
}
}
}) => {
return (
<tr>
<td>{ID}</td>
<td>{description_data.map(({value}) =>value).join(",")}</td>
<td>{exploitabilityScore}</td>
<td>{severity}</td>
<td>{impactScore}</td>
</tr>
);
});
I have a top level JSON structure as follows:
{
"video": [],
"messages": [],
"notifications": []
}
and i have a database output (in variable "result") as follows i want to push into the "video" array:
[
{
"_id": "5f98ab906439155cfc6f9afb",
"status": "NOT_STARTED",
"date": "2020-10-27T23:21:52.683Z",
"callInvitees": [
{
"username": "user1"
},
{
"username": "user2"
}
]
},
{
"_id": "5f98aba0789e163e0c78908f",
"status": "NOT_STARTED",
"date": "2020-10-27T23:22:08.048Z",
"callInvitees": [
{
"username": "user1"
}
]
}
]
My code is:
let dashboardJSON = { "video": [], "messages": [], "notifications": [] };
dashboardJSON.video.push(result)
It works but i am ending up with too many arrays (i think) - it looks as follows:
{
"video": [
[
{
"_id": "5f98ab906439155cfc6f9afb",
"status": "NOT_STARTED",
"date": "2020-10-27T23:21:52.683Z",
"callInvitees": [
{
"username": "user1"
},
{
"username": "user2"
}
]
},
{
"_id": "5f98aba0789e163e0c78908f",
"status": "NOT_STARTED",
"date": "2020-10-27T23:22:08.048Z",
"callInvitees": [
{
"username": "user1"
}
]
}
]
],
"messages": [],
"notifications": []
}
I want "video": [ { ... }, { ... } ] whereas i have "video": [[ { ... }, { ... } ]]
How can i resolve this?
You can use the spread operator as follows:
let result = [
{
"_id": "5f98ab906439155cfc6f9afb",
"status": "NOT_STARTED",
"date": "2020-10-27T23:21:52.683Z",
"callInvitees": [
{
"username": "user1"
},
{
"username": "user2"
}
]
},
{
"_id": "5f98aba0789e163e0c78908f",
"status": "NOT_STARTED",
"date": "2020-10-27T23:22:08.048Z",
"callInvitees": [
{
"username": "user1"
}
]
}
]
let dashboardJSON = { "video": [], "messages": [], "notifications": [] };
dashboardJSON.video.push(...result)
console.log(dashboardJSON);
Just use Array.prototype.map() method. Map method returns a new array with the result by using the provided function.
const ret = {
video: [],
messages: [],
notifications: [],
};
const data = [
{
_id: '5f98ab906439155cfc6f9afb',
status: 'NOT_STARTED',
date: '2020-10-27T23:21:52.683Z',
callInvitees: [
{
username: 'user1',
},
{
username: 'user2',
},
],
},
{
_id: '5f98aba0789e163e0c78908f',
status: 'NOT_STARTED',
date: '2020-10-27T23:22:08.048Z',
callInvitees: [
{
username: 'user1',
},
],
},
];
ret.video = data.map((x) => x);
console.log(ret);
I'm trying to query my dataset for two purposes:
Match a term (resellable = true)
Order the results by their price
lowest to highest
Data set/doc is:
"data" : {
"resellable" : true,
"startingPrice" : 0,
"id" : "4emEe_r_x5DRCc5",
"buyNowPrice" : 0.006493, //Changes per object
"sub_title" : "test 1",
"title" : "test 1",
"category" : "Education",
}
//THREE OBJECTS WITH THE VALUES OF 0.006, 0.7, 1.05 FOR BUYNOWPRICE
I have three objects of these with different buyNowPrice
Query with agg is:
{
"query": {
"bool": {
"must": [
{
"term": {
"data.resellable": true
}
}
]
}
},
"from": 0,
"size": 5,
"aggs": {
"lowestPrice": {
"terms": {
"field": "data.buyNowPrice",
"order": {
"lowest_price": "desc"
}
},
"aggs": {
"lowest_price": {
"min": {
"field": "data.buyNowPrice"
}
},
"lowest_price_top_hits": {
"top_hits": {
"size": 5,
"sort": [
{
"data.buyNowPrice": {
"order": "desc"
}
}
]
}
}
}
}
}
}
The query works fine, and the results are 3 objects that have resellable = true
The issue is, the agg is not organizing the results based off the lowest buy now price.
Each result, the order of buyNowPrice is: 1.06, 0.006, 0.7 - which is not ordered properly.
Switching to desc has no affect, so I don't believe the agg is running at all?
EDIT:
Using the suggestion below my query now looks like:
{
"query": {
"bool": {
"must": [
{
"term": {
"data.resellable": true
}
}
]
}
},
"from": 0,
"size": 5,
"aggs": {
"lowestPrice": {
"terms": {
"field": "data.buyNowPrice",
"order": {
"lowest_price": "asc"
}
},
"aggs": {
"lowest_price": {
"min": {
"field": "data.buyNowPrice"
}
},
"lowest_price_top_hits": {
"top_hits": {
"size": 5
}
}
}
}
}
}
With the results of the query being:
total: { value: 3, relation: 'eq' },
max_score: 0.2876821,
hits: [
{
_index: 'education',
_type: 'listing',
_id: '4emEe_r_x5DRCc5', <--- buyNowPrice of 0.006
_score: 0.2876821,
_source: [Object]
},
{
_index: 'education',
_type: 'listing',
_id: '4ee_r_x5DRCc5', <--- buyNowPrice of 1.006
_score: 0.18232156,
_source: [Object]
},
{
_index: 'education',
_type: 'listing',
_id: '4444_r_x5DRCc5', <--- buyNowPrice of 0.7
_score: 0.18232156,
_source: [Object]
}
]
}
EDIT 2:
Removing the query for resellable = true the aggregation will sort properly and return the items in the proper order. But with the query for resellable included, it does not.
I'm assuming this has to do with the _score property overriding the sorting from agg? How would this be fixed
You can use a bucket sort aggregation that is a parent pipeline
aggregation which sorts the buckets of its parent multi-bucket
aggregation. Zero or more sort fields may be specified together with
the corresponding sort order.
Adding a working example (using the same index data as given in the question), search query, and search result
Search Query:
{
"query": {
"bool": {
"must": [
{
"term": {
"data.resellable": true
}
}
]
}
},
"from": 0,
"size": 5,
"aggs": {
"source": {
"terms": {
"field": "data.buyNowPrice"
},
"aggs": {
"latest": {
"top_hits": {
"_source": {
"includes": [
"data.buyNowPrice",
"data.id"
]
}
}
},
"highest_price": {
"max": {
"field": "data.buyNowPrice"
}
},
"bucket_sort_order": {
"bucket_sort": {
"sort": {
"highest_price": {
"order": "desc"
}
}
}
}
}
}
}
}
Search Result:
"buckets": [
{
"key": 1.0499999523162842,
"doc_count": 1,
"highest_price": {
"value": 1.0499999523162842
},
"latest": {
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.08701137,
"hits": [
{
"_index": "stof_64364468",
"_type": "_doc",
"_id": "3",
"_score": 0.08701137,
"_source": {
"data": {
"id": "4emEe_r_x5DRCc5",
"buyNowPrice": 1.05 <-- note this
}
}
}
]
}
}
},
{
"key": 0.699999988079071,
"doc_count": 1,
"highest_price": {
"value": 0.699999988079071
},
"latest": {
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.08701137,
"hits": [
{
"_index": "stof_64364468",
"_type": "_doc",
"_id": "2",
"_score": 0.08701137,
"_source": {
"data": {
"id": "4emEe_r_x5DRCc5",
"buyNowPrice": 0.7 <-- note this
}
}
}
]
}
}
},
{
"key": 0.006000000052154064,
"doc_count": 1,
"highest_price": {
"value": 0.006000000052154064
},
"latest": {
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.08701137,
"hits": [
{
"_index": "stof_64364468",
"_type": "_doc",
"_id": "1",
"_score": 0.08701137,
"_source": {
"data": {
"id": "4emEe_r_x5DRCc5",
"buyNowPrice": 0.006 <-- note this
}
}
}
]
}
}
}
]
Update 1:
If you modify your search query as :
{
"query": {
"bool": {
"must": [
{
"term": {
"data.resellable": true
}
}
]
}
},
"aggs": {
"lowestPrice": {
"terms": {
"field": "data.buyNowPrice",
"order": {
"lowest_price": "asc" <-- change the order here
}
},
"aggs": {
"lowest_price": {
"min": {
"field": "data.buyNowPrice"
}
},
"lowest_price_top_hits": {
"top_hits": {
"size": 5
}
}
}
}
}
}
Running the above search query also, you will get your required results.
newFormName = req.body.name;
newFormQuestions = req.body.questions;
formId = req.body.formId;
User.updateOne(
{
"forms._id": formId,
},
{
$set: {
"forms.$.name": newFormName,
"forms.$.questions": newFormQuestions,
},
},
(errUpdate, resultUpdate) => {
if (errUpdate) {
return res.status(500).json({ sucess: false, error: errUpdate });
} else {
return res.status(200).json({ sucess: true, data: resultUpdate });
}
}
);
the above code is responsible to update certain field in the user database.
Example of how user data looks like
[{
"enrolledEventID": [],
"isOrganiser": true,
"isAdmin": false,
"forms": [
{
"questions": [
{
"questionType": "Text",
"textInputLabelName": "asdsadsad"
},
{
"questionType": "Text",
"textInputLabelName": "asdasdasdasd"
}
],
"_id": "5f6070b5002a5249b050bd1e",
"name": "Test Form 4",
"dateCreated": "2020-09-15T07:43:49.389Z",
"__v": 0
},
{
"questions": [
{
"questionType": "Text",
"textInputLabelName": "asdsadsad"
},
{
"questionType": "Text",
"textInputLabelName": "asdasdasdasd"
}
],
"_id": "5f607140cd6faa39241f7c8a",
"name": "Test Form 56",
"dateCreated": "2020-09-15T07:46:08.012Z",
"__v": 0
},
{
"questions": [
{
"questionType": "Rating",
"textInputQuestionTitle": "asdasdasd",
"totalRating": 0
},
{
"questionType": "Text",
"textInputLabelName": "asdasdasdasd"
},
{
"questionType": "Text",
"textInputLabelName": "asdasdasdasdasd"
}
],
"_id": "5f6315145e6c794e78bcce73",
"name": "New Form",
"dateCreated": "2020-09-17T07:49:40.307Z",
"__v": 0
},
{
"questions": [
{
"questionType": "Rating",
"textInputQuestionTitle": "asdasdasdsadad",
"totalRating": 0
}
],
"_id": "5f6316895e6c794e78bcce74",
"name": "New Formasdasdasd",
"dateCreated": "2020-09-17T07:55:53.537Z",
"__v": 0
},
{
"questions": [
{
"questionType": "Text",
"textInputLabelName": "asdsadsad"
},
{
"questionType": "Text",
"textInputLabelName": "asdasdasdasd"
}
],
"_id": "5f632b0f12f05d5028c96942",
"name": "Test Form 23232323",
"dateCreated": "2020-09-17T09:23:27.137Z",
"__v": 0
}
],
"_id": //id,
"fullname": //name,
"email": //hotmail,
"password": //password,
"__v": 0
},
{
"enrolledEventID": [],
"isOrganiser": true,
"isAdmin": false,
"forms": [],
"_id": //id,
"fullname": //name,
"email": //email,
"password": //password,
"__v": 0
} ]
and the problem is that the match will always return 0, I'm new to mongoose and it seems that I should be able to access to the forms._id through "forms._id" in the criteria after done some research, what did I do wrong ?
I have ensured that the formId is existed in the user data.
Make sure newFormQuestions have the same object keys with questions.
Do console.log for every step you aren't sure of.
As an alternative for this mongoose update, use
const temp = User.find({forms._id:formId}) first,
then you could use User.save() after assigning the value into the object you've found.
Good Luck ^^