Update JSON variable based on Mongoose results - json

I have a JSON variable outside of mongoDB collection as below
var outputJson = [
{
'Product' : 'TV',
'isSelected': 0
},
{
'Product' : 'Radio',
'isSelected': 0
},
{
'Product' : 'Book',
'isSelected': 0
},
{
'Product' : 'Watch',
'isSelected': 0
}
]
Now I want to update the isSelected key if the product exits in MongoDB; I want something like below
var outputJson = [
{
'Product' : 'TV',
'isSelected': 0
},
{
'Product' : 'Radio',
'isSelected': 1
},
{
'Product' : 'Book',
'isSelected': 0
},
{
'Product' : 'Watch',
'isSelected': 1
}
]
Here is the code that I am trying, but I am not getting the above result
outputJson.forEach(function(key,value){
wishlistData.find({userID:req.user.id}, function(err,data{
data.forEach(function(k,i){
if (data[i].product=== outputJson[value].Product){
outputJson[value].isSelected = 1
}
})
});
})
Any help is appreciated

Firstly, the callback function to forEach is called with the item in the array as the first argument, so data[i] and outputJson[value] are redundant.
You should make use of mongoose's findOne method to see if there's at least one match, and you can pass in Product as follows
outputJson.forEach(function(item) {
wishlistData.findOne({userID: req.user.id, product: item.Product}, function(err, data) {
if (data !== null) { // if it actually found a match
item.isSelected = 1;
}
});
});
But keep in mind that mongoDB queries are asynchronous, so outputJson would still be the same right after the forEach loop. You might want to use promises and Promise.all to ensure that you do stuff with outputJson after all the queries have been processed:
Promise.all(outputJson.map(function(item) {
return wishlistData.findOne({userID: req.user.id, product: item.Product}).then(function(err, data) {
if (data !== null) { // if it actually found a match
item.isSelected = 1;
}
});
})).then(function() {
// do stuff with outputJson here
});

Replace this
if (data[i].product=== outputJson[value].Product){
outputJson[value].isSelected = 1
}
by
if (data[k].product=== outputJson[key].Product){
outputJson[key].isSelected = 1
}
each callback function have first argument as index

First thing, why are you doing the same mongo query repeatedly for each object in the Array, as it will give you the same result. Also use the lodash library 'lodash'. This is how you can achieve this:
var _ = require('lodash')
wishlistData.find({userID:req.user.id}, function (err, data) {
var dataMap = _.indexBy(data, "product");
outputJson.forEach(function(key,value){
if(!_.isEmpty(_.get(dataMap, key.Product))) {
key.isSelected = 1;
}
})
}

Thank you #Ambyjkl, you guidence worked Promise made the trick, I made minor changes to your script and it started working
Promise.all(outputJson.map(function(i,k) {
return wishlistData.findOne({userID: req.user.id, product: i.Product}).then(function(data, err) {
if (data !== null) { // if it actually found a match
i.isSelected = 1;
}
});
})).then(function() {
console.log(outputJson);
});

Related

Console.log json specific value

I'm working with some script and I would like to ask how to display on the console a specific json value.
For example, I have script:
Promise.all([
fetch('https://blockchain.info/balance?active=3C6WPNa5zNQjYi2RfRmt9WUVux7V4xbDmo').then(resp => resp.json()),
fetch('https://api.binance.com/api/v3/avgPrice?symbol=BTCEUR').then(resp => resp.json()),
]).then(console.log)
output:
[{
3C6WPNa5zNQjYi2RfRmt9WUVux7V4xbDmo: {
final_balance: 185653,
n_tx: 1,
total_received: 185653
}
}, {
mins: 5,
price: "19230.49330261"
}]
I want to console price and final_balance.
Best regards!
One way you could achieve this is by flattening the array and objects within because there's no predefined structure of what the output looks like.
Here, I'm assuming the output you mentioned is always an array of objects.
const flattenObject = (obj = {}) =>
Object.keys(obj || {}).reduce((acc, cur) => {
if (typeof obj[cur] === "object") {
acc = { ...acc, ...flattenObject(obj[cur]) };
} else {
acc[cur] = obj[cur];
}
return acc;
}, {});
const outputs = [
{
"3C6WPNa5zNQjYi2RfRmt9WUVux7V4xbDmo": {
final_balance: 185653,
n_tx: 1,
total_received: 185653,
},
},
{
mins: 5,
price: "19230.49330261",
},
];
outputs.forEach((output) => {
const flatOutput = flattenObject(output);
console.log("flatOutput:", flatOutput);
if (flatOutput.final_balance) {
console.log("final_balance:", flatOutput.final_balance);
}
if (flatOutput.price) {
console.log("price:", flatOutput.price);
}
});

RowDataPacket returns empty object but it is not empty [React/Next]

I've been stressing around trying to fix this and I've burnt myself out. I'm calling my serverless mysql trying to get kanbans from teams. I've used this method multiple times and all were working fine but that is most likely because of they only return single item whilst this returns multiple items.
This is my code which returns empty object.
async function getKanbans(team_id){
let kanbans = [];
await sql_query(`SELECT id, sName FROM table WHERE iTeam = ?`, [team_id])
.then(result => {
result.forEach(kanban => {
// console.log(kanban);
kanbans.push({
id: kanban.id,
name: kanban.sName
});
});
})
.catch(err => {
console.log(err);
});
console.log(kanbans);
return kanbans;
}
As you can see.. I am trying to print kanbans and I do get:
[
{ id: 1, name: 'Kanban_1' },
{ id: 2, name: 'Kanban_2' }
]
of out it. Then I'm trying to return it to the item that called this function and this is how that looks like:
teams.push({
id : team.id,
sName : team.sName,
sColor : team.sColor,
aKanbans : result[0]['selectedTeam'] == team.id ? getKanbans(team.id) : null,
});
(a small snippet of something bigger)
Okay, so now when I try and look at the data response (from the frontend) I get this:
{
"success": true,
"message": "Found teams",
"teams": [
{
"id": 1,
"sName": "Team1",
"sColor": "#fcba03",
"aKanbans": {}
},
{
"id": 2,
"sName": "Team2",
"sColor": "#2200ff",
"aKanbans": null
}
]
}
aKanbans from Team1 is empty, empty object. What the **** do I do? I tried mapping it and still got an empty object. React/javascript is not my main language, I just like to learn. Any suggestions?
You are mixing async / await function with normal Promises handling.
Try to change your getKanbans code like this:
async function getKanbans(team_id) {
let kanbans = [];
try {
const result = await sql_query(
`SELECT id, sName FROM table WHERE iTeam = ?`,
[team_id]
);
result.forEach((kanban) => {
kanbans.push({
id: kanban.id,
name: kanban.sName,
});
});
} catch (err) {
console.log(err);
}
return kanbans;
}
And then populate the teams using (declare the parent async):
teams.push({
id : team.id,
sName : team.sName,
sColor : team.sColor,
aKanbans : result[0]['selectedTeam'] == team.id ? getKanbans(team.id) : null,
});

Sequelize - query other table inside where clause

I am trying to do something and do not know if this is possible with sequelize. Basically I have this code snippet running on graphQl and basically what this does is to find kits on the kits table and then verify if the same id exists on the "users" table. If not, it returns them, if yes it does not. However now we need to scale this to have pagination and the current snippet is not so scalable. That is why I had the idea to just include the for loop in the where clause or somehow to check there, but really do not know any command on mySql that allows to do this.
Do you have any tip?
async findKitsWithResultNoReg2(_, {search}) {
try {
let promises = []
const a1 = await db.kits.findAll({
where: {
[Op.and]: [
{ result: { [Op.or]: [1, 2, 3] } },
{ cp: 0 },
{[Op.or]: [
{ kitID: { [Op.like]: '%' + search + '%' } }]}
]
}
})
for (let i = 0; i < a1.length; i++) {
const a2 = await db.users.findByPk(a1[i].dataValues.kitID)
if (a2 === null) {
const a3 = {
kitID: a1[i].dataValues.kitID,
result: a1[i].dataValues.result,
date: a1[i].dataValues.resultDate
}
promises.push(a3)
}
}
return Promise.all(promises)
} catch (error) {
console.log(error)
}
},
async findKitsWithResultNoReg() {
try {
const a0 = await sequelize.query(`SELECT kitID, result, resultDate from kits where result in (1,2,3) and cp = 0 and archived = 0 and not Exists(select kitID from users where kits.kitID = users.kitID) order by resultDate desc`, { type: QueryTypes.SELECT })
const a1 = JSON.stringify(a0)
return a1
} catch (error) {
console.log(error)
}
},

How to get filtered the array in json reponse based on condition check with keys in angular 7

I would like to get filterd the particular array alone from the json response when dataID is not matched with the ParentDataID from another array in same json response using typescript feature in Angular 7
{ "data":[
{
"dataId":"Atlanta",
"parentDataId":"America"
},
{
"dataId":"Newyork",
"parentDataId":"America"
},
{
"dataId":"Georgia",
"parentDataId":"Atlanta"
},
{
"dataId":"South",
"parentDataId":"Atlanta"
},
{
"dataId":"North",
"parentDataId":"South"
}
]
}
In above response the value of dataId Newyork is not matched with any of the parentDataId entire array json response. So Now i want to filtered out only the second array of DataID alone to make new array.
I would like to have this validation in Typescript angular 7
My output is supposed to like below... The DataId does not have the parentDataId
[
{
"dataId":"Newyork",
"parentDataId":"America"
},
{
"dataId":"Georgia",
"parentDataId":"Atlanta"
},
{
"dataId":"North",
"parentDataId":"South"
}
]
Appreciate the help and response
You can use filter method:
let filterKey = 'Atlanta';
const result = data.data.filter(f=> f.parentDataId != filterKey
&& f.dataId != filterKey);
An example:
let data = { "data":[
{
"dataId":"Atlanta",
"parentDataId":"America"
},
{
"dataId":"Newyork",
"parentDataId":"America"
},
{
"dataId":"Georgia",
"parentDataId":"Atlanta"
}
]
};
let filterKey = 'Atlanta';
const result = data.data.filter(f=> f.parentDataId != filterKey
&& f.dataId != filterKey);
console.log(result);
demo in this StackBlitz Link
my solution is like below code snippet. ts
reducedData = [...this.data];
this.data.reduce((c,n,i) => {
this.data.reduce((d,o, inex) => {
if ( n.dataId === o.parentDataId){
this.reducedData.splice(i,1, {'dataId': 'removed', parentDataId: 'true'});
} else {
return o;
}
},{});
return n;
}, {});
this.reducedData = this.reducedData.filter (value => value.dataId !== 'removed');
html file
<h4> dataId does not have parentId </h4>
<hr>
<pre>
{{reducedData | json}}
</pre>
EDIT
If you do not want to use second object reducedData, then below solution is fine to work.. StackBlitz Link
component.ts
this.data.reduce((c,n,i) => {
this.data.reduce((d,o, inex) => {
if ( n.dataId === o.parentDataId) {
this.data[i]['removed'] = "removed";
} else{
return o;
}
},{});
return n;
}, {});
this.data = this.data.filter (value => value['removed'] !== 'removed');
component.html
<h4> dataId does not have parentId </h4>
<hr>
<pre>
{{data |json}}
</pre>
Please try like this.
const data = { "data":[
{
"dataId":"Atlanta",
"parentDataId":"America"
},
{
"dataId":"Newyork",
"parentDataId":"America"
},
{
"dataId":"Georgia",
"parentDataId":"Atlanta"
}
]
};
const filterKey = "Newyork"
const matchExist = data.data.some( item => item.parentDataId === filterKey && item.dataId === filterKey)
let filteredArray ;
if(!matchExist){
filteredArray = data.data.find(item => item.dataId === filterKey )
}

Unable to access inner JSON value in JSON array - Typescript(Using Angular 8)

I am trying to use the group by function on a JSON array using the inner JSON value as a key as shown below. But unable to read the inner JSON value. Here is my JSON array.
NotificationData = [
{
"eventId":"90989",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{
"externalId":"2434",
"priority":"1"
}
}
},
{
"eventId":"6576",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{
"externalId":"78657",
"priority":"1"
}
}
}
]
GroupBy Logic:
const groupBy = (array, key) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
return result;
}, {});
};
const serviceOrdersGroupedByExternalId = groupBy(this.NotificationData, 'event.ServiceOrder.externalId');
//this line of code is not working as
// it is unable to locate the external id value.
Desired output
{ "2434":[{
"eventId":"90989",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{ "priority":"1" }
}
}],
"78657":[{
"eventId":"6576",
"eventTime":"2019-12-11T11:20:53+04:00",
"eventType":"yyyy",
"event":{
"ServiceOrder":{ "priority":"1" }
}
}]
}
Does this solves your purpose?
let group = NotificationData.reduce((r, a) => {
let d = r[a.event.ServiceOrder.externalId] = [...r[a.event.ServiceOrder.externalId] || [], a];
return r;
}, {});
console.log(group);
Try like this:
result = {};
constructor() {
let externalIds = this.NotificationData.flatMap(item => item.event.ServiceOrder.externalId);
externalIds.forEach(id => {
var eventData = this.NotificationData.filter(
x => x.event.ServiceOrder.externalId == id
).map(function(item) {
delete item.event.ServiceOrder.externalId;
return item;
});
this.result[id] = eventData;
});
}
Working Demo