Related
I have a [simplified] JSON file like
{
"id":87,
"meta_data":[
{
"id":1232,
"key":"user_created_by",
"value":"example#gmail.com"
},
{
"id":1233,
"key":"user_created_at",
"value":"1659890457477"
},
{
"id":1234,
"key":"good_person_or_silly_sausage",
"value":"No"
}
]
}
I want to do something like
Logger.log(orderDetailsObject.meta_data.value[key="good_person_or_silly_sausage"])
The expected value would be
No
However, this isn't what's occurring. At present I'm being told that the object is null.
I think it's because the meta_data object is an object in an object or two dimensional array or something? I don't have a good understand of what I'm doing here,
I feel like
https://docs.jsonata.org/simple
and
https://docs.jsonata.org/predicate
Should be guiding me towards the answer - but I'm not getting something I think.
I'm a newbie to SO and JSON & Javascript - so please be gentle. <3
EDIT: None-simplified actual json file below:
{
"id":87,
"parent_id":0,
"status":"pending",
"currency":"USD",
"version":"6.5.1",
"prices_include_tax":false,
"date_created":"2022-08-07T16:40:57",
"date_modified":"2022-08-11T10:13:07",
"discount_total":"0.00",
"discount_tax":"0.00",
"shipping_total":"0.00",
"shipping_tax":"0.00",
"cart_tax":"0.00",
"total":"1100.00",
"total_tax":"0.00",
"customer_id":17,
"order_key":"wc_order_omQo7nW5yCS9X",
"billing":{
"first_name":"",
"last_name":"",
"company":"",
"address_1":"",
"address_2":"",
"city":"",
"state":"",
"postcode":"",
"country":"",
"email":"freddie#example.com",
"phone":""
},
"shipping":{
"first_name":"",
"last_name":"",
"company":"",
"address_1":"",
"address_2":"",
"city":"",
"state":"",
"postcode":"",
"country":"",
"phone":""
},
"payment_method":"",
"payment_method_title":"",
"transaction_id":"",
"customer_ip_address":"",
"customer_user_agent":"",
"created_via":"rest-api",
"customer_note":"",
"date_completed":null,
"date_paid":"2022-08-07T16:40:58",
"cart_hash":"",
"number":"87",
"meta_data":[
{
"id":1232,
"key":"user_created_by",
"value":"example#gmail.com"
},
{
"id":1233,
"key":"user_created_at",
"value":"1659890457477"
},
{
"id":1234,
"key":"good_person_or_silly_sausage",
"value":"No"
},
{
"id":1235,
"key":"order_request_high_chair",
"value":"yes"
},
{
"id":1240,
"key":"order_notes",
"value":"They're on their honeymoon"
},
{
"id":1241,
"key":"pricing_notes",
"value":"They're on their honeymoon"
},
{
"id":1242,
"key":"order_booked_by",
"value":"me on me"
},
{
"id":1243,
"key":"order_referral_source",
"value":"Newspaper"
},
{
"id":1244,
"key":"commission_percent",
"value":"13"
},
{
"id":1245,
"key":"discount_percent",
"value":"5"
},
{
"id":1246,
"key":"deposit_paid_date",
"value":"today"
},
{
"id":1247,
"key":"damage_bond_date_paid",
"value":"today"
},
{
"id":1248,
"key":"damage_bond",
"value":"100"
},
{
"id":1249,
"key":"start_date",
"value":"01\/01\/01"
},
{
"id":1250,
"key":"deposit_payment_amount",
"value":"500"
},
{
"id":1251,
"key":"order_request_welcome_pack_wine_type",
"value":"Red"
},
{
"id":1252,
"key":"end_date",
"value":"02\/02\/02"
},
{
"id":1259,
"key":"_new_order_email_sent",
"value":"true"
},
{
"id":1260,
"key":"_automatewoo_order_created",
"value":"1"
}
],
"line_items":[
{
"id":45,
"name":"Villa Booking",
"product_id":0,
"variation_id":0,
"quantity":1,
"tax_class":"",
"subtotal":"1000.00",
"subtotal_tax":"0.00",
"total":"1000.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":411,
"key":"Dates",
"value":"01\/01\/01 until 02\/02\/02",
"display_key":"Dates",
"display_value":"01\/01\/01 until 02\/02\/02"
}
],
"sku":null,
"price":1000,
"parent_name":null
},
{
"id":46,
"name":"Standard Welcome Pack",
"product_id":73,
"variation_id":0,
"quantity":2,
"tax_class":"",
"subtotal":"0.00",
"subtotal_tax":"0.00",
"total":"0.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":421,
"key":"Wine Type",
"value":"Red",
"display_key":"Wine Type",
"display_value":"Red"
}
],
"sku":"",
"price":0,
"parent_name":null
}
],
"tax_lines":[
],
"shipping_lines":[
],
"fee_lines":[
{
"id":47,
"name":"Damage Bond",
"tax_class":"",
"tax_status":"taxable",
"amount":"100",
"total":"100.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":428,
"key":"damage_bond_paid_to",
"value":"example#gmail.com",
"display_key":"damage_bond_paid_to",
"display_value":"example#gmail.com"
},
{
"id":429,
"key":"damage_bond_paid_on",
"value":"today",
"display_key":"damage_bond_paid_on",
"display_value":"today"
}
]
},
{
"id":48,
"name":"Booking Fee",
"tax_class":"",
"tax_status":"taxable",
"amount":"",
"total":"0.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":436,
"key":"dbooing_fee_paid_to",
"value":"example#gmail.com",
"display_key":"dbooing_fee_paid_to",
"display_value":"example#gmail.com"
},
{
"id":437,
"key":"booking_fee_paid_on",
"value":"1659890457477",
"display_key":"booking_fee_paid_on",
"display_value":"1659890457477"
}
]
}
],
"coupon_lines":[
],
"refunds":[
],
"payment_url":"https:\/\/dev1.example.com\/checkout\/order-pay\/87\/?pay_for_order=true&key=wc_order_omQo7nW5yCS9X",
"date_created_gmt":"2022-08-07T16:40:57",
"date_modified_gmt":"2022-08-11T10:13:07",
"date_completed_gmt":null,
"date_paid_gmt":"2022-08-07T16:40:58",
"currency_symbol":"$",
"_links":{
"self":[
{
"href":"https:\/\/dev1.example.com\/wp-json\/wc\/v3\/orders\/87"
}
],
"collection":[
{
"href":"https:\/\/dev1.example.com\/wp-json\/wc\/v3\/orders"
}
],
"customer":[
{
"href":"https:\/\/dev1.example.com\/wp-json\/wc\/v3\/customers\/17"
}
]
}
}
You can use the find method on the array:
const orderDetailsObject = {"id":87,"meta_data":[{"id":1232,"key":"user_created_by","value":"example#gmail.com"},{"id":1233,"key":"user_created_at","value":"1659890457477"},{"id":1234,"key":"good_person_or_silly_sausage","value":"No"}]};
console.log(orderDetailsObject.meta_data.find(
({key}) => key == "good_person_or_silly_sausage"
)?.value);
I am using mongodb aggregation with a collection named files
that has a relationship with another collection named file_upload.
files = {
type: String,
media: { type: Schema.Types.ObjectId, ref: 'file_upload', required: true },
}
file_upoad = {
name: String,
}
This is the query
const data = await strapi.query('files').model.aggregate([
{
$lookup: {
from: "analytics",
localField: "_id",
foreignField: "file_id",
as: "hits",
}
},
{ $unwind: '$hits' },
{ $group: { _id: "$_id", hitsCount: { $sum: 1 } } },
{ $sort: { hitsCount: -1 } },
{ $limit: 1 },
])
my goal is to retrieve the media as part of the result since it is a relationship field, at the moment I get this
[
{
"_id": "61fd74367b6ee77b89bae34d",
"hitsCount": 12
},
{
"_id": "61fd74367b6ee77b89sddfee",
"hitsCount": 8
}
]
expected result
[
{
"_id": "61fd74367b6ee77b89bae34d",
"hitsCount": 12,
"media": {
name:"name1"
}
},
{
"_id": "61fd74367b6ee77b89sddfee",
"hitsCount": 8,
"media": {
name:"name2"
}
}
]
I'm new in mongodb and try small project and document are design just like below
products
[
{
_id:ObjectId('60d87d6fafd7a1377c03b2e6'),
productName:"noodles instant",
description:"lorem ipsum ... ... ...."
},
{
_id:ObjectId('60d87d6fafd7a1377c03b2e7'),
productName:"Sandal",
description:"lorem ipsum ... ... ...."
}
]
and my transaction document has structure is just like below
transactions
[
{
_id:ObjectId('60d8781031308dbf565eaaa8'),
trasactionSerial:"TRS20210000001",
transactionDate:2021-06-27T13:30:23.369+00:00,
productInTransactions:[
{
_id:ObjectId('60d8781031308dbf565eaab9'),
productId:ObjectId('60d87d6fafd7a1377c03b2e6'),
qty:1500
},
{
_id:ObjectId('60d8781031308dbf565eaa47'),
productId:ObjectId('60d87d6fafd7a1377c03b2e7'),
qty:200
}
]
},
{
_id:ObjectId('60d8781031308dbf565eaab7'),
trasactionSerial:"TRS20210000002",
transactionDate:2021-06-27T13:32:23.369+00:00,
productInTransactions:[
{
_id:ObjectId('60d8781031308dbf565eaab9'),
productId:ObjectId('60d87d6fafd7a1377c03b2e6'),
qty:100
},
{
_id:ObjectId('60d8781031308dbf565eaa47'),
productId:ObjectId('60d87d6fafd7a1377c03b2e7'),
qty:300
}
]
}
]
from the transaction I hope will get some result like below from the same date in transactionDate field
result
[
{
_id:ObjectId('60d87d6fafd7a1377c03b2e6'),
productName:"noodles instant",
qtyInTransaction:1600
},
{
_id:ObjectId('60d87d6fafd7a1377c03b2e7'),
productName:"Sandal",
qtyInTransaction:500
},
]
sorry maybe my English is poor to elaborate it
thanks for any feedback and your help
Use the $lookup stage which has $group in its pipeline option.
db.products.aggregate([
{
"$lookup": {
"from": "transactions",
"let": {
"pId": "$_id"
},
"pipeline": [
{
"$unwind": "$productInTransactions"
},
{
"$match": {
"$expr": {
"$eq": [
"$productInTransactions.productId",
"$$pId"
]
},
},
},
{
"$group": {
"_id": "$$pId",
"qtyInTransaction": {
"$sum": "$productInTransactions.qty"
}
},
},
],
"as": "matchedTransactions"
}
},
{
"$project": {
"_id": 1,
"description": 1,
"qtyInTransaction": {
"$arrayElemAt": [
"$matchedTransactions.qtyInTransaction",
0
]
}
},
},
])
Mongo Playground Sample Execution
So, I'm relatively new to javascript, and I'm working with a client-side javascript function that inserts JSON results pushed to it from the server.
I would like to stop certain results, independently of that javascript that populating the results.
Usually, if the js was my own, I'd make a guess that I'd use the "splice" function to remove the JSON array entry(ies) that I don't wish to be there, does that sound about right? (I'd got to there through plenty of searching on StartPage and here)
However, I need whatever function I (let's be honest, "you") come up with to trump the embedded results.
Essentially this is normal behaviour:
Webpage > JavaScript Parses JSON for Initial Results
then
Webpage > Scroll > JavaScript Parses JSON for More Results
I'd like to insert something that will stop any JSON items that I don't like. I don't know how to represent that, I'd assume:
Worker in Extension/Add-On > Webpage > etc
I doubt this can be done with CSS ... but that'd be awesome, as I'd just put it in my personal.
If it was splice, I'd have a vague idea (but really I'm flying blind) of how to do it on a base level with splice, but I'm already struggling, and that would deepen for the insanely deeply embedded objects I'm trying to exclude.
So. There is lot of json data in the section I'm looking at.
I'm purely concentrated on the removing of the array here, but by end goal is two parts:
In the ' contents ' array in levelOneB's ' daContentShaper ' I would
like to remove any item from the array where in the sub-object '
content ' there is an element called ' contentTypeA '. There's another
object with the label ' ahThisIsTheBContent ', which I'd also like gone,
and that's dotted through the JSON. All other items (TypeB, TypeC, or
other) must stay.
Additionally, within said ' content ' object I would like to change any ' visible ' values that are " false " to " true ".
It's definitely possible, it's just working out how to ensure that the rest of the code (which may have similar - not the same - parts elsewhere) isn't affected by my splice of this array.
{
"levelOneA": {
"levelOneAArr": [ { "name": "me", "age": 1 }, { "name": "you", "age": 2 }, { "name": "them", "age": 3 } ],
"levelOneAText": "blah"
},
"levelOneB": {
"levelOneBDeepBro": {
"levelOneBDeepBroTabs": [
{
"levelOneBDeepBroTabsShaper": {
"isBlessed": true,
"daContent": {
"daContentShaper": {
"contents": [
{
"contentItem": {
"content": {
"contentTypeA": {
"bitA": "bitAText",
"bitB": [
{
"bitBText1": "cripes"
},
{
"bitBText1": "crikey"
},
{
"bitBText1": "crimeny"
}
],
"visible": true
}
},
"extraNonsense": "bingoBlah"
}
},
{
"contentItem": {
"content": {
"ahThisIsTheBContent": {
"bitA": "bitAText",
"bitB": [
{
"bitBText1": "cripes"
},
{
"bitBText1": "crikey"
},
{
"bitBText1": "crimeny"
}
],
"visible": false
}
},
"extraNonsense": "bingoBlahBlah"
}
},
{
"contentItem": {
"content": {
"contentTypeB": {
"bitA": "bitAText",
"bitB": [
{
"bitBText1": "jinkies"
},
{
"bitBText1": "ruh roh"
},
{
"bitBText1": "like, wow"
}
],
"visible": true
}
},
"extraNonsense": "bingoBlahBlah"
}
},
{
"contentItem": {
"content": {
"contentTypeC": {
"bitA": "bitAText",
"bitB": [
{
"bitBText1": "cripes"
},
{
"bitBText1": "crikey"
},
{
"bitBText1": "crimeny"
}
],
"visible": true
}
},
"extraNonsense": "bingoBlahBlahBlah"
}
}
],
"myDadIsBetter": "Go Faster Stripes, innit."
}
},
"tabId": "Bro"
}
}
]
}
},
"levelOneC": "CAAQhGciEwi0iqD5-ZbwAhUBPvEFHQMKAeo=",
"levelOneD": {
"iAmJustHappyToBeNominated": "innit",
"damnYourWholePopCultureSubsection": "flames abound"
}
}
This is how you could solve this using object-scan
Note that I used quite a few ** in the matching. You could write these out exactly, it depends on your requirement
// const objectScan = require('object-scan');
const data = { levelOneA: { levelOneAArr: [{ name: 'me', age: 1 }, { name: 'you', age: 2 }, { name: 'them', age: 3 }], levelOneAText: 'blah' }, levelOneB: { levelOneBDeepBro: { levelOneBDeepBroTabs: [ { levelOneBDeepBroTabsShaper: { isBlessed: true, daContent: { daContentShaper: { contents: [ { contentItem: { content: { contentTypeA: { bitA: 'bitAText', bitB: [ { bitBText1: 'cripes' }, { bitBText1: 'crikey' }, { bitBText1: 'crimeny' } ], visible: true } }, extraNonsense: 'bingoBlah' } }, { contentItem: { content: { ahThisIsTheBContent: { bitA: 'bitAText', bitB: [ { bitBText1: 'cripes' }, { bitBText1: 'crikey' }, { bitBText1: 'crimeny' } ], visible: false } }, extraNonsense: 'bingoBlahBlah' } }, { contentItem: { content: { contentTypeB: { bitA: 'bitAText', bitB: [ { bitBText1: 'jinkies' }, { bitBText1: 'ruh roh' }, { bitBText1: 'like, wow' } ], visible: false } }, extraNonsense: 'bingoBlahBlah' } }, { contentItem: { content: { contentTypeC: { bitA: 'bitAText', bitB: [ { bitBText1: 'cripes' }, { bitBText1: 'crikey' }, { bitBText1: 'crimeny' } ], visible: false } }, extraNonsense: 'bingoBlahBlahBlah' } } ], myDadIsBetter: 'Go Faster Stripes, innit.' } }, tabId: 'Bro' } } ] } }, levelOneC: 'CAAQhGciEwi0iqD5-ZbwAhUBPvEFHQMKAeo=', levelOneD: { iAmJustHappyToBeNominated: 'innit', damnYourWholePopCultureSubsection: 'flames abound' } };
const logic = {
'levelOneB.**.daContentShaper.contents[*].*.content.{contentTypeA,ahThisIsTheBContent}': ({ key, parents }) => {
parents[3].splice(key[key.length - 4], 1);
},
'levelOneB.**.daContentShaper.contents.**.visible': ({ value, parent, property }) => {
if (value === false) {
parent[property] = true;
}
}
};
const modify = objectScan(Object.keys(logic), {
rtn: 'count',
filterFn: ({ matchedBy, property, key, value, parent, parents }) => {
matchedBy.forEach((m) => logic[m]({ property, key, value, parent, parents }));
}
});
console.log(modify(data));
// => 6
console.log(data);
// => { levelOneA: { levelOneAArr: [ { name: 'me', age: 1 }, { name: 'you', age: 2 }, { name: 'them', age: 3 } ], levelOneAText: 'blah' }, levelOneB: { levelOneBDeepBro: { levelOneBDeepBroTabs: [ { levelOneBDeepBroTabsShaper: { isBlessed: true, daContent: { daContentShaper: { contents: [ { contentItem: { content: { contentTypeB: { bitA: 'bitAText', bitB: [ { bitBText1: 'jinkies' }, { bitBText1: 'ruh roh' }, { bitBText1: 'like, wow' } ], visible: true } }, extraNonsense: 'bingoBlahBlah' } }, { contentItem: { content: { contentTypeC: { bitA: 'bitAText', bitB: [ { bitBText1: 'cripes' }, { bitBText1: 'crikey' }, { bitBText1: 'crimeny' } ], visible: true } }, extraNonsense: 'bingoBlahBlahBlah' } } ], myDadIsBetter: 'Go Faster Stripes, innit.' } }, tabId: 'Bro' } } ] } }, levelOneC: 'CAAQhGciEwi0iqD5-ZbwAhUBPvEFHQMKAeo=', levelOneD: { iAmJustHappyToBeNominated: 'innit', damnYourWholePopCultureSubsection: 'flames abound' } }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#14.3.0"></script>
Disclaimer: I'm the author of object-scan
I have a mongodb collection called cases and inside cases I have an array of cases per company object.
So the structure is:
Inside each case I want to use the createddate (which is a string) and endDate (also string) and convert it to a mongodb date.
When I use NoSQLBooster I add the following query:
db.cases.aggregate([
{ $match: { companyID: 218 }},
{ $unwind: "$cases" },
{ $match: { 'cases.id': '299' }},
{ $addFields: { 'cases.created': new Date('2010-06-21T00:00:00.000'), 'cases.closed': new Date('2014-08-29T00:00:00.000') }},
{ $group: { _id: "$_id", cases: { $push: "$cases" }}}])
This will add a date in a new field - created and then closed. This is exactly what I want.
However, in my code (using mongoose) I have the following:
scripts.commponent.ts:
runThroughCasesAndConvertDates(id) {
this.scriptsService.getAllCasesToModify({ companyID : id}).subscribe( res => {
if (res.length > 0) {
for (let i = 0; i < res[0].cases.length; i++) {
const caseID = res[0].cases[i].id;
const data = {
companyID: id,
caseID: caseID,
created: moment(res[0].cases[i].createddate, 'DD-MMM-YYYY h:mm a').format('YYYY-MM-DD[T00:00:00.000Z]'),
closed: ''
};
if (res[0].cases[i].endDate !== '') {
data.closed = moment(res[0].cases[i].endDate, 'DD-MMM-YYYY h:mm a').format('YYYY-MM-DD[T00:00:00.000Z]');
}
this.scriptsService.updateDates(data).subscribe();
}
}
});
}
scripts.service.ts
updateDates(body) {
return this.http.post('/db/cases/updateAllDates', body).pipe(
map(res => res.json())
);
}
casesDB.js
router.post('/updateAllDates', (req, res) => {
const { body } = req;
Cases.aggregate([
{ $match: { companyID: body.companyID }},
{ $unwind: "$cases" },
{ $match: { 'cases.id': body.caseID }},
{ $addFields: { 'cases.created': new Date(body.created), 'cases.closed': new Date(body.closed) } },
{ $group: { _id: "$_id" }
}],
function (err, data) {
res.json(data)
});
});
But it does not add anything into the array. Im really confused as to what Im doing wrong. Maybe there is a better way / approach to doing this?
Thank you
You can $map over the cases array and can change the date string fields to date object fields.
Cases.aggregate([
{ "$addFields": {
"cases": {
"$map": {
"input": "$cases",
"in": {
"$mergeObjects": [
"$$this",
{
"createddate": {
"$dateFromString": { "dateString": "$$this.createddate" }
},
"endDate": {
"$dateFromString": { "dateString": "$$this.endDate" }
}
}
]
}
}
}
}}
])
Update: If dates are blank string
Cases.aggregate([
{ "$addFields": {
"cases": {
"$map": {
"input": "$cases",
"in": {
"$mergeObjects": [
"$$this",
{
"createddate": {
"$cond": [
{ "$eq": ["$$this.createddate", ""] },
null
{ "$dateFromString": { "dateString": "$$this.createddate" } }
]
},
"endDate": {
"$cond": [
{ "$eq": ["$$this.endDate", ""] },
null
{ "$dateFromString": { "dateString": "$$this.endDate" } }
]
}
}
]
}
}
}
}}
])