Meteor Import JSON into Collection - javascript

I am trying to import a JSON file that has embedded objects into the MongoDB and would like to know how to format to import the doc correctly. To be clear the doc format must remain in its current form. I must modify/create a function or method that would allow this file to be imported with _id associated in the sport-events array loop (Ive shorted to one sports-event array for brevity). Perhaps a better way of putting the question is how could I import eveything in the sports-event array and leave the rest of the doc.
JSON Doc.
{
"sports-content": {
"sport-event": [{
"event-metadata": {
"league": "NCAA Basketball",
"event-type": "0",
"league-details": "NCAAB",
"event-date-time": "12/18/2015 07:00 PM",
"eventNum": "3000460",
"status": "",
"off-the-board": "False"
},
"team": [{
"team-metadata": {
"alignment": "Home",
"nss": "526",
"openNum": "526",
"name": {
"full": "Clemson"
}
},
"wagering-stats": {
"wagering-straight-spread": {
"bookmaker-name": "BetOnline",
"active": "true",
"line": "1.5",
"money": "-110",
"context": "current"
}
},
"team-stats": {
"score": "0"
}
}, {
"team-metadata": {
"alignment": "Away",
"openNum": "525",
"nss": "525",
"name": {
"full": "South Carolina"
}
},
"wagering-stats": {
"wagering-straight-spread": {
"bookmaker-name": "BetOnline",
"active": "true",
"line": "-1.5",
"money": "-110",
"context": "current"
}
},
"team-stats": {
"score": "0"
}
}]
}],
"sports-meta-data": {
"doc-time": "42353.5979256944"
}
}
}
Meteor server.js under Meteor.startup
if (SportEventsFeed.find().count() === 0) {
console.log("Importing private/products.json to db")
var data = JSON.parse(Assets.getText("ncaab.json"));
data.forEach(function (item, index, array) {
SportEventsFeed.insert(item);
})
}

Here is how you can just insert the items from the 'sports-event' array as individual documents in the db.
I'm not sure if the index value is what you wanted for the _id field, if not change the value assigned to item_id (or comment out this line for a default _id).
if (SportEventsFeed.find().count() === 0) {
console.log("Importing private/products.json to db")
var data = JSON.parse(Assets.getText("ncaab.json"));
data['sports-content']['sports-event'].forEach(function (item, index, array) {
item._id = index;
SportEventsFeed.insert(item);
})
}

Related

Matching Object with 2 arrays with same key but different values from JSON API and compare to state values and return that Object

I've been trying for days to figure out the best approach and also how to make it work. I'm building a product page and each variation options is built dynamically (size, color) based on the GraphQL response it gets back. I'm used to simpler array checking but this one has me baffled and at a lost for even where to start.
So when a user clicks on "M" and "Red" it takes those values and stores them into state
// State Setup
const [variations, setVariations] = useState({});
// Set Variations State that was selected
function productVariationsHandler(event) {
setVariations({ ...variations, [event.target.name]: event.target.value });
}
// State Object after user has made their selections
{
"variations": {
"color": "Red",
"size": "XL"
}
}
I'm trying to take those user selected state variables ("Red", "XL") and match them to the GraphQL response in the variations object to get the databaseId and regularPrice
// GraphQL Response
{
"variations": {
"nodes": [
{
"attributes": {
"nodes": [
{
"attributeId": 237,
"name": "pa_color",
"value": "True Royal"
},
{
"attributeId": 220,
"name": "pa_size",
"value": "S"
}
]
},
"databaseId": 1846,
"regularPrice": "$24.95",
"salePrice": null,
"status": "publish"
},
{
"attributes": {
"nodes": [
{
"attributeId": 237,
"name": "pa_color",
"value": "Red"
},
{
"attributeId": 221,
"name": "pa_size",
"value": "XL"
}
]
},
"databaseId": 1847,
"regularPrice": "$24.95",
"salePrice": null,
"status": "publish"
}
]
}
}
I've tried using the find method and as well as map and even tried for as seen below but without avail
// My Failed Attempt
// Find the Variation based on user selected options
function findVariationProduct() {
for (const key in variations) {
product.variations.nodes.map((variation) => {
const variationProduct = variation.attributes.nodes.find(
({ value, name }) => {
if (name == `pa_${key}` && value == variations[key]) {
console.log(variationProduct);
}
}
);
});
}
}
Any help would be greatly appreciated!

Updating MongoDB nested array using same path as the search query

I have the following problem, I want to update a document with a path id.metadata.panels.items where panels is an array and items is an array. My search query looks at the items and displays only those that match the criteria of metadata.panels.items.member.type: 'owner' - then I want to update the 'owner to 'account'.
When I am trying to update having the search path same as update path I get an error message saying: cannot use the part metadata.panels.items.member.type to traverse the element.
The documents have their own
How can I resolve this problem?
I have already tried to go through the collection using nested forEach statements to iterate through each of the arrays but I am not sure what to do next.
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
var newFields = [];
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
})
})
})
Sample document structure:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Owner]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
Expected result:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Account]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
I figured it out.
var newFields = [];
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
// I have generated update statements as strings
// first list is always position 0 and this goes to the statement
// second list get's populated from itemIndex
// added them to the newFields list
})
})
})
newFields.forEach(function(i){
eval(i)
})

Get back the whole JSON request from google action with Node js client library

I am using actions-on-goolge library for nodejs https://www.npmjs.com/package/actions-on-google
How would I able to get the whole JSON response, or use id string inside my intent function? I have tried to print out the input, it only gives the query part of the JSON. Tried to look up their documentation, it does not seem to explain how I could get back the whole JSON file.
https://developers.google.com/actions/reference/nodejs/lib-v1-migration
I am beginner of javascript.
The JSON request from simulator:
{
"user": {
"userId": "ABwppHEAPgcgb2yFUFURYFEJGg4VdAVcL9UKO9cS7a7rVfasdasdt67LzgrmMseTvb5mmJjbjj7UV",
"locale": "en-US",
"lastSeen": "2018-05-11T23:14:42Z",
"userStorage": "{\"data\":{}}"
},
"conversation": {
"conversationId": "1526080586367",
"type": "NEW"
},
"inputs": [
{
"intent": "com.example.device.OFF",
"rawInputs": [
{
"inputType": "KEYBOARD",
"query": "Talk to MyDevice to turn off"
}
],
"arguments": [
{
"name": "trigger_query",
"rawText": "turn off",
"textValue": "turn off"
}
]
}
],
"surface": {
"capabilities": [
{
"name": "actions.capability.MEDIA_RESPONSE_AUDIO"
},
{
"name": "actions.capability.WEB_BROWSER"
},
{
"name": "actions.capability.AUDIO_OUTPUT"
},
{
"name": "actions.capability.SCREEN_OUTPUT"
}
]
},
"isInSandbox": true,
"availableSurfaces": [
{
"capabilities": [
{
"name": "actions.capability.AUDIO_OUTPUT"
},
{
"name": "actions.capability.SCREEN_OUTPUT"
}
]
}
]
}
My Node JS script base on the example:
const express = require('express')
const bodyParser = require('body-parser')
const {
actionssdk,
Image,
} = require('actions-on-google')
app.intent('actions.intent.TEXT', (conv, input) => {
if (input === 'bye' || input === 'goodbye') {
return conv.close('See you later!')
}
conv.ask(`I didn't understand. Can you tell me something else?`)
})
app.intent('com.example.MyDevice.TEST', (conv, input) => {
console.log(input);
console.log(conv.action);
console.log(conv.intent);
conv.close('Test Done');
});
express().use(bodyParser.json(), app).listen(3000)
You should be able to get the entire JSON request through conv.body.

Nested forEach issue

I have two arrays of object, the first array (printers, around 80 elements) is made of the following type of objects:
[{
printerBrand: 'Mutoh',
printerModel: 'VJ 1204G',
headsBrand: 'Epson',
headType: '',
compatibilty: [
'EDX',
'DT8',
'DT8-Pro',
'ECH',
],
cartridges: [],
},
....
]
The second array (cardridges, around 500 elements) is made of the following type of objects:
[
{
"customData": {
"brand": {
"value": {
"type": "string",
"content": "ECH"
},
"key": "brand"
},
"printer": {
"value": {
"type": "string",
"content": "c4280"
},
"key": "printer"
}
},
"name": "DT8 XLXL",
"image": {
"id": "zLaDHrgbarhFSnXAK",
"url": "https://xxxxxxx.net/images/xxxxxx.jpg"
},
"brandId": "xxxxx",
"companyId": "xxxx",
"createdAt": "2018-03-26T14:39:47.326Z",
"updatedAt": "2018-04-09T14:31:38.169Z",
"points": 60,
"id": "dq2Zezwm4nHr8FhEN"
},
...
]
What I want to do first is to is to iterate through the first array and and then iterate for all the cardridge available: if a the value customData.brand.value of a cardridge is included inside the array 'compatibility' of a printer, then I have to add this cardridge object inside the cardridges array of this printer. I have tried but somehow the iteration doesn't take place correctly. This is what I tried:
printers.forEach((printerItem) => {
const printer = printerItem;
printer.compatibilty.forEach((compatibilityItem) => {
const compatibility = compatibilityItem;
cardridges.forEach((cartridge) => {
if (compatibility === cartridge.customData.brand.value.content) {
printer.cartridges.push(cartridge);
}
});
});
});
What am I doing wrong?
You're accessing the wrong property. It should be cartridge.customData.brandName.value.content, carefully note brandName.value rather than brand.value
Your issue is that you're accessing it by the wrong property - brand and not brandName.
Furthermore, if you're targeting everything but IE, you could simplify your nested for loops to utilize some fancy ES6 array methods.
printers.forEach((p) => {
p.cartridges.push(cartridges.filter((c) => {
const brandName = c.customData.brandName.value.content;
return p.compatibilty.includes(brandName);
}));
});

Replace array element from rethinkdb if it exists,or else insert

{
"LOGIN": "ABC",
"MESSAGE_UNPROCESSED": [
{
"DATE": "20160219",
"MESSAGE": [
{
"address": "XYZ",
"date": "1468385398746"
},
{
"address": "PQR",
"date": "1468385398746"
}
]
},
{
"DATE": "20160220",
"MESSAGE": [
{
"address": "LMN",
"date": "1468385398746"
},
{
"address": "JXT",
"date": "1468385398746"
}
]
}
],
"id": "e1705cae-2a57-42b3-af2e-8458ae9a43bb"
}
I want to add message into the field where Login is ABC if DATE doesn't exist or if it exist I want to replace the entire object from doc
I tried this :
r.db('usersData').table('smsRaw').filter(function (row) {
return row('MESSAGE_UNPROCESSED')('DATE').contains('20160222').replace({"DUMP":"DUMP"})
})
error: Cannot nest writes or meta ops in stream operations. Use FOR_EACH instead in:
r.db("usersData").table("smsRaw").filter(function(var_13) {
return var_13("MESSAGE_UNPROCESSED")("DATE").contains("20160222").replace({"DUMP": "DUMP"});
})
so if records {"DATE":"2016018","MESSAGE":[{"address":"abc","Date":"121212"}]}
if this record doesn't exist in MESSAGE_UNPROCESSED it should be added using set_insert or else if date is existing like 2016020 then entire element from array should be replaced
r.db('usersData').table('smsRaw').get("7cd66671-bb01-483d-a148-12ed1b7c2d31").update(function(row) {
return {
MESSAGE_UNPROCESSED: r.branch(
row("MESSAGE_UNPROCESSED")('DATE').eq('20160222'),
row("MESSAGE_UNPROCESSED")('MESSAGE').merge({"DUMP":"DUMP"}),
row("MESSAGE_UNPROCESSED")('MESSAGE').replace({"NEW":"NEW"})
)
}
})
Cannot nest writes
I want to do this manipulation using python

Categories