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

{
"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

Related

Mapping JSON response to using JS

I have a JSON response coming in and I need to map it into an Object and return only the specific fields using js.
Here I have created an example response:
{
"Header": {
"SenderId": "IDMAN",
},
"Shipments": {
"Shipment": [
{
"ShipmentNumber": "KIOKLIOS32",
"Product": {
"value": "1234",
"description": "example desc"
},
"Services": {
"Service": [
{
"value": "0234",
"amount": null,
"unit": null,
}
]
},
...
}
There will be multiple Service's and I need the fields shipments.shipment.product.value and shipments.shipment.services.service.value (all of them from the list).
One of my ideas was to first try create a const:
if (response.status === 200) {
let data = await response.text();
const shipmentData = JSON.parse(data);
const destination = {
"Header": {
"SenderId": _.get(shipmentData, 'Header.SenderId'),
}
};
res.status(200)
.send(destination);
}
This way I can get the senderId but I cannot access the array.
In which way do I have to create my object to map all of this?

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);
}));
});

How to delete a paticular Object in an array inRethinkDB

I am Just trying to learn RethinkDB.I am little Bit Confused That how to delete an single Object in an array,What is the Exact query I have to use if i have to delete this Object
{
"name": "Ram" ,
"username": "B97bf210-c4d2d-11e6-b783-07b5fev048705"
}
from whoLikedIt Array
My data
{
"comments": [ ],
"id": "c242c74d-03d9-4963-9a22-4779facb8192" ,
.....
"views": 0 ,
"whoLikedIt": [
{
"name": "Vignesh Warar" ,
"username": "d97bf210-c42d-11e6-b783-07b5fe048705"
},
{
"name": "Ram" ,
"username": "B97bf210-c4d2d-11e6-b783-07b5fev048705"
},
]
.....
}
My Try
r.db('image').table('posts').get('c242c74d-03d9-4963-9a22-4779facb8192').update(
{whoLikedIt:r.row('whoLikedIt').filter({username:"B97bf210-c4d2d-11e6-b783-07b5fev048705"}).delete()}
)
Throws Me a error
e: Cannot nest writes or meta ops in stream operations. Use FOR_EACH instead in:
You want:
r.db('image').table('posts').get('c242c74d-03d9-4963-9a22-4779facb8192').update(function(row) {
return {whoLikedIt: row('whoLikedIt').filter(function(obj) {
return obj('username').ne("B97bf210-c4d2d-11e6-b783-07b5fev048705");
})};
})

Meteor Import JSON into Collection

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);
})
}

Categories