Wix Velo Database Query Has No Results - json

I am attempting to query my database called battery2221 but keep getting no results. I've read all the API documentation but can't seem to find the problem. Any feedback is greatly appreciated. Here is my page code:
import wixData from 'wix-data';
$w.onReady(function () {
//TO DO: Write Your Page Related Code Here:
})
export function button1_click(event, $w) {
//Add your code for this event here:
getVINInfo($w("#vininput").value)
.then(VINInfo => {
console.log(VINInfo)
let year = VINInfo.Results[9].Value;
let make = VINInfo.Results[6].Value;
let model = VINInfo.Results[8].Value;
let engine = VINInfo.Results[71].Value + " " + "Liters"
let car = VINInfo.Results[9].Value + " " + VINInfo.Results[6].Value + " " + VINInfo.Results[8].Value;
wixData.query("battery2221")
.include("title")
.eq("year", year)
.eq("make", make)
.eq("model", model)
.find()
.then((results) => {
console.log(results);
$w("#results").text = "Vehicle Specific Battery for Your" + " " + car;
Here is what the developers console shows when I run the code:
_query:
{...}
jsonTableCopy JSON
orderBy:
"undefined"
invalidArguments:
[...]
filterTree:
{...}
jsonTableCopy JSON
$and:
Array(3)
jsonTableCopy JSON
0:
{...}
jsonTableCopy JSON
year:
"2019"
1:
{...}
jsonTableCopy JSON
make:
"HONDA"
2:
{...}
jsonTableCopy JSON
model:
"Civic"
{
"$and": [
{
"year": "2019"
},
{
"make": "HONDA"
},
{
"model": "Civic"
}
]
}
This code has worked when the Wix language was Corvid but since switching to Velo the code no longer functions.
What I need is to query the battery2221 database for the year, make and model from the VINInfo results. The result should be the battery reference field (field name is “title” in the database) from the database.
Any and all feedback is appreciated 😊

Related

discord.js 12 any way to send data from json file to channel?

I have json file, that contains info about some players, that looks like this
{
"208505383361314816": {
"warns": 8,
"reason": "test"
},
"776387838350196756": {
"warns": 99,
"reason": ""
}
}
Then I sort the information by the number of warns. It works perfectly, but i have no idea, how to send a message.
client.on('message', message => {
if (message.content.startsWith('>topw')) {
const sorted = [];
const keys = Object.keys(warns)
for (let user in warns) {
const warny = warn[user].warns;
const entry = {
[keys[sorted.length]]: warns[user]
}
if (sorted.length === 0) {
sorted.push(entry);
continue;
}
let i = 0;
while (sorted[i] !== undefined && sorted[i][Object.keys(sorted[i])].warns > warny) {
i++;
}
sorted.splice(i, 0, entry)
}
console.log(sorted)
}
})
It should look like a "leaderboard", but with amount of warns
e.g:
name: Bob
warns: 20
reason: test
Welcome to StackOverflow! :)
About your JSON file
First of all, quick advice regarding the way you store data: you really, really should store the user info in an array, it would look like that:
[
{
"id": "00000000",
"warns": 10,
"reason": "test"
}
]
Getting your data ready
That being said, let's answer your question.
I guess that you'd love to use MessageEmbeds, take a look at the docs before reading the code, it might help. I will also rewrite a little bit of your code.
Reformating it
To make our life easier, we'll reformat the data so we can sort it.
// It's just your JSON file here
const oldWarns = {
"208505383361314816": {
"warns": 8,
"reason": "test"
},
"776387838350196756": {
"warns": 99,
"reason": ""
}
}
let newWarns = Object.keys(oldWarns).map((e) => ({
id: e,
warns: oldWarns[e].warns,
reason: oldWarns[e].reason
}))
console.log(newWarns)
Sorting it
Now that we've got this beautiful array, let's sort it. It's much simpler than you think!
// Precedently generated data
let newWarns = [{
"id": "208505383361314816",
"warns": 8,
"reason": "test"
},
{
"id": "776387838350196756",
"warns": 99,
"reason": ""
}
]
newWarns.sort((a, b) => (a.warns > b.warns ? 1 : -1))
console.log(newWarns)
Sending the data
What you actually asked for.
Rendering it with an embed
Alright, everything is set so we can send the data. Here's how to use embeds in Discord.js.
const warnBoard = new Discord.MessageEmbed()
.setTitle("Warnboard")
.setColor("#FF0000")
.addFields(newWarns.flatMap((e, i) => ( // flatMap will delete all the [] of the array after mapping it
i >= 25 ? [] : { // the max number of fields in embeds is 25
name: e.id,
value: e.warns,
inline: true // changes the layout
}
)))
I just used a few of MessageEmbed's features. They can be really nice looking, so feel free to mess around with its props!
Making it as simple as it can get
Embeds are too much? You can also just send a string.
const stringifiedData = JSON.stringify(newWarns, null, 4)
const warnBoard = "```json\n"+ stringifiedData +"\n```"
Send it
Whether the solution you chose is the string or the embed, this is the way you're gonna send the data.
message.channel.send(warnBoard)

How to get data from database in array format using node js and MySql

I am using node.js as server language and Mysql as database so I am running query and getting data from database but is is showing in format like this
[ BinaryRow { name: 'Dheeraj', amount: '77.0000' },
BinaryRow { name: 'Raju', amount: '255.0000' } ]
What I want is
['Dheeraj', 77.0000],
['Raju', 66255.000030],
This what I am doing in my backend (node.js):
My model:
static getChartData(phoneNo, userType) {
let sql = 'select businessname as name,sum(billamt) amount from cashbackdispdets where consphoneno =' + phoneNo + ' group by businessid order by tstime desc limit 10'
return db.execute(sql, [phoneNo]);
My controller:
exports.getColumnChart = function(req, res) {
const phoneNo = req.body.userId
const userType = req.body.userType
console.log(phoneNo)
dashboardModule.getChartData(phoneNo, userType)
.then(([rows]) => {
if (rows.length > 0) {
console.log(rows)
return res.json(rows)
} else {
console.log("error")
return res.status(404).json({ error: 'Phone No. already taken' })
}
})
.catch((error) => {
console.log(error)
return res.status(404).json({ error: 'Something went wrong !!' })
})
}
I am sending this data to Ui and when I am receiving it on UI it is in the form of object inside array which is not the required data type I want
axios().post('/api/v1/Dashboard/DashboardColumnChart',this.form)
.then(res=>{
console.log(res.data)
debugger
this.chartData= res.data
})
The above code consoles on browser like
I am not getting any idea how o do it should I do it with backend or with front end and how
Nodejs will send you a JSON response if you want to change it. It is better to change or maniuplate it in a Front end framework. But if you want to change it in backend as you have asked Make sure that the rows is in the format that you want to recive.
let data = [
{ "name": "Dheeraj", "amount": "77.0000" },
{ "name": "Raju", "amount": "255.0000" }
]
// empty array to store the data
let testData = [];
data.forEach(element => {
testData.push(element.name)
});
You can format it using array.map and Object.values. map functions loops over each element and returns a modified element according to the callback provided. Object.values simply returns all the values of an object in an array.
const data = [ { "name": "Dheeraj", "amount": "77.0000" }, { "name": "Raju", "amount": "255.0000" } ];
const formattedData = data.map(obj => Object.values(obj));
console.log("Initial Data: ", data);
console.log("Formatted Data: ", formattedData);
// Map function example
const a = [1,2,3]
const mappedA = a.map(e => e * 2)
console.log(a, " mapped to: ", mappedA);
// Object.values example
const b = { firstName: 'John', lastName: 'Doe', number: '120120' }
console.log(Object.values(b));

Getting a JSON and adding it to an array

I have following JSON file:
{
"fruites": [
{"id" :"f1", "name": "apple", "selected": "false"},
{"id": "f2" , "name":"orange", "selected": "false"}
]
}
Here is my JSON interface:
export interface FruitsType {
id: String;
name: String;
selected : String;
}
Not sure if this is a correct an interface.
I WANT TO USE THE NAME OF THE FRUITES AS VALUE FOR A CHECKBOX
To read this JSON I have following service:
getJSON (): Observable<JSON> {
return this.http.get<JSON>((this.configUrl))
}
}
In my component I have follwowing code to read the get the JSON file:
this.jsonService.getJSON().subscribe(response => {
console.log(response.fruites);
console.log(response.fruites[1].name);
console.log(response.fruites.length);
for (this.i = 0; this.i < response.fruites.length; this.i++) {
console.log("id" + response.fruites[this.i ].id);
console.log("name" + response.fruites[this.i].name);
console.log("selected" + response.fruites[this.i].selected);
}
})
in the browser I can see that it works, while in the consule where i am running the ng serve I see the following error:
src/app/componenets/home/home.component.ts(221,41): error TS2339: Property 'fruites' does not exist on type 'JSON'.
The other thing is that I cannot push this to an array, I use the follwoing code:
this.jsonArray.push(response.fruites[this.i].name )
AND
this.jsonArray.push(response.fruites)
AND
this.jsonArray.push(response)
All returs eithr undefined or nothing at all!
Please consult me on these.
I believe the payload you are getting can be easily done as:
this.jsonService.getJSON().subscribe(response => {
for(const i of response.fruites) { // Iterate over the list
console.log('Data set coming as - ', i);
console.log('ID - ', i.id);
console.log('Name - ', i.name);
console.log('Selected - ', i.selected);
}
array=[]; var item;
response.fruites.map((item) =>{ array.push(item.name)});
console.log('Array with name', array);`
Try it
response.json().fruites
or
response.data.fruites
in this post , I have posted the full answer of how I got everything done which also relates to this question I have asked.

How to solve Unexpected token p in JSON at position 3 using angular2 or typescript

When i go to save the survey content after editing, i get this error,
SyntaxError: Unexpected token p in JSON at position 3
at JSON.parse (<anonymous>)
Please anyone help me to solve this issue, I am hereby pasting my codes, please help.
ts code:
Surveypost = () => {
let token = this.auth.getAccessTokenId();
console.log(token)
let currentUser = this.auth.getCurrentUserData();
console.log(this.editor.text)
console.log(this.survey_val)
// let survey_json = JSON.parse(this.editor.text);
let survey_json:any;
try{
survey_json = JSON.parse(this.editor.text);
} catch(e) {
/*Handle the error scenario here*/
}
let survey_data = {
"value": survey_json,
};
console.log(survey_data)
this.AdminAPI
.createandSet(survey_data, token)
.subscribe(
survey => {
console.log(survey)
}, error => {
console.log(error);
}
);
}
I am getting the consoled output till, console.log(this.editor.text), then error comes.
The consoled output of console.log(this.editor.text) starts like this,
{
pages: [
{
name: "page1",
elements: [
{
type: "radiogroup",
name: "price",
title: "How long have you been a customer at {companyname}?",
isRequired: true,
choices: [
{
value: "less",
text: "0 - 3 months."
},
{
value: "medium",
text: "3 - 12 months."
},
{
value: "High",
text: "12 + months."
}
]
this.editor.text contains an invalid JSON.
When trying to parse that invalid JSON the error occurs. So in short terms, the following line is the one that crash: let survey_json = JSON.parse(this.editor.text);
Grab the output from the console.log(this.editor.text), run it trough a JSON validator/formatter like:
https://jsonformatter.curiousconcept.com/
And then you should be able to easily see why the error occurs, and why the program is not able to parse the JSON
EDIT FROM WHEN JSON HAS BEEN ADDED
AS you can see from the link mentioned above, the JSON is not valid, and that is the reason for the error message on the line: let survey_json = JSON.parse(this.editor.text);.
For instance a basic JSON should have the following structure:
{
"key" : "value",
"key2" : "value2"
}
You are also not ending the JSON correctly. I've formatted the JSON to a valid JSON here:
{
"pages":[
{
"name":"page1",
"elements":[
{
"type":"radiogroup",
"name":"price",
"title":"How long have you been a customer at {companyname}?",
"isRequired":true,
"choices":[
{
"value":"less",
"text":"0 - 3 months."
},
{
"value":"medium",
"text":"3 - 12 months."
},
{
"value":"High",
"text":"12 + months."
}
]
}
]
}
]
}
When you are trying to parse some text sent from a 3rd party source, it is a good idea to wrap the parse logic with a try catch block.
But do remember that this should be done only after fixing the trivial bugs in the remote source(that is, if you have access, of course).
replace,
let survey_json = JSON.parse(this.editor.text);
with,
let survey_json;
try{
survey_json = JSON.parse(this.editor.text);
} catch(e) {
/*Handle the error scenario here*/
/*Lets assign an empty object(or possibly a default value) instead*/
survey_json = {};
}

How to convert a MongoDB document to JSON Object

I am trying to make a post request with the MongoDB document returned from find query, as the request body in NodeJS.But on the server I'm getting the Error : Invalid JSON. Below is the document that I'm trying to POST
{
"_id" : ObjectId("5739a6bf3f1b41477570dc89"),
"taskCount" : 2,
"study" : "cod",
"phase" : "mansa2",
"rhimeTaskId" : "5739a6bec4567f6e737fd3db",
"recordId" : "5726f3cfc4567f6e737fc3ab",
"recordStudy" : "codstudy",
"recordPhase" : "mansa2",
"recordLanguage" : "Punjabi",
"recordScript" : "Latin",
"_state" : "CodingComplete",
"tasks" : [
{
"physician" : ObjectId("5739a6bd3f1b41477570dc78"),
"stage" : "Coding",
"result" : {
"cod" : "C15",
"feedback" : {
"narrativeLength" : "Adequate",
"positiveSymptomsIncluded" : "Only Positive",
"certainty" : "High"
},
"keywords" : [
"52 yr male, died of food pipe cancer, suffered pain upper abdomen, investigated,FNAC confirmed Cancer, Put on Chemotherapy, multiple cycles, died at home, had fever with chills occasionally"
]
}
},
{
"physician" : ObjectId("5739a6bd3f1b41477570dc79"),
"stage" : "Coding",
"result" : {
"cod" : "C15",
"feedback" : {
"narrativeLength" : "Inadequate",
"positiveSymptomsIncluded" : "Only Positive",
"certainty" : "High"
},
"keywords" : [
"severe pain abdomen, ultrasonography revealed food pipe cancer, chemotherapy given, died"
]
}
}
],
"__v" : 2
}
and here is the code that I wrote to make the POST request
var MongoClient = require('mongodb').MongoClient;
var request = require('request');
var assert = require('assert');
var cmeprovisioning= 'mongodb://localhost:27017/cmeprovisioning';
MongoClient.connect(cmeprovisioning, function(err, db) {
assert.equal(null, err);
var count=0;
console.log("Connected to cmeprovisioning");
var cursor =db.collection('rhimeReport').find(
{"study":"cod","phase":"mansa2","recordStudy":"codstudy",
"recordPhase":"mansa2","_state":"CodingComplete"
});
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
count=count+1;
request({url: "http://cme.host.net:8081/cme-provisioning/update",
method: "POST",json: true,
headers: {"content-type": "application/json"},
json: doc
},function(e,r,b){
console.log("POST Error "+count+" "+e)
console.log("POST Response "+count+" "+r)
console.log("POST BODY "+count+" "+b)
});
} else {
console.log("Some Error : "+err)
}
});
});
I also tried using JSON.stringify(doc), but still got the Invalid JSON error. Is there a way I can use mongo document returned by the find query and convert it to JSON to make the POST request.
I think those ObjectID is what making it an invalid JSON document.
Here's the actual answer:
If you want to convert a mongo object to JSON object.
There's a utility method in every mongo object toJSON
So you can simply do mongoResponseObject.toJSON() on the response object.
e.g.
Products.findById(id).then(res => {
const jsonRes = res.toJSON();
// Here jsonRes is JSON
})
Alternatively you can directly get the JSON object by using the .lean() like this.
Products.findById(id).lean().then(res => {
// Here res is JSON
})
you need to convert object id to string ie.
var result = {
"_id": ObjectId("5739a6bf3f1b41477570dc89"),
"taskCount": 2,
"study": "cod"
};
//now convert to string
result=result._id.toString();
//now you can use the result
Try this,
var cursor =db.collection('rhimeReport').find(
{"study":"cod","phase":"mansa2","recordStudy":"codstudy",
"recordPhase":"mansa2","_state":"CodingComplete"});
cursor.toString();
......
Hope this help.
Try this in robomongo
var cursor = db.getCollection('X').find({},{})
while(cursor.hasNext()) {
print(JSON.stringify(cursor.next()))
}