Express returns empty Array, but array is fine - arrays

All things are going right, when I try to log array it writes everything true but when I try to return as response, it goes empty to front-end. I'm not sure why this is happening, the normal messages array works fine. I don't know why.
console.log('messageye girdi');
MessageModel.find({
receiver: req.body.uuid,
read: false
}).then((Messages) => {
function removeDups(names) {
let unique = {};
names.forEach(function(i) {
if (!unique[i]) {
unique[i] = true;
}
});
return Object.keys(unique);
}
let Users = [];
Messages.forEach(Message => {
Users.push(Message.sender);
})
const nonduplicate = removeDups(Users);
console.log(nonduplicate);
const MessageUsers = [];
var bu = 0;
nonduplicate.forEach(User => {
UserModel.findOne({
uuid: User
}).then((UserData) => {
console.log(UserData.username);
MessageUsers.push(UserData.username);
console.log(MessageUsers);
})
bu++;
if (bu = nonduplicate.length) {
console.log("bu mu acaba " + JSON.stringify(MessageUsers));
let ArrayVer = Object.assign({}, MessageUsers);
return res.send({
success: true,
users: MessageUsers
});
}
});

Related

Memory heap keeps increasing using ag-grid, angular and websocket

We needed to create a Live Monitor sort of screen that gets the feed through a WebSocket. Angular 11 is used for the UI part. When the page is left on Chrome for a few minutes, the memory heap starts increasing and gradually it increases to a greater extent. After some time, the application will hang and we can't go to another page of the application.
I'm unable to understand the cause of the memory leak, if any.
HTML Code:
<ag-grid-angular #LiveHedgeGrid class="ag-theme-balham" [rowData]="hedgeRowData" [columnDefs]="hedgeColumn" (gridReady)="onLiveHedgeReady($event)" (columnRowGroupChanged)="oncolumnRowGroupChanged($event)" (gridSizeChanged)="onGridSizeChanged($event)"
[enableCellChangeFlash]="true" [rowBuffer]="10" [debounceVerticalScrollbar]="true" [suppressColumnVirtualisation]="true" [groupIncludeTotalFooter]="true" [gridOptions]="gridOptions" [suppressAggFuncInHeader]="true" [groupDefaultExpanded]="groupDefaultExpanded"
[domLayout]="domLayout">
</ag-grid-angular>
TypeScript Code:
websocketCall() {
let socket = new WebSocket(ApiService.webSocketUrl);
socket.onopen = e => {
};
socket.onmessage = e => {
let server_message;
try {
server_message = JSON.parse(e.data);
server_message = JSON.parse(server_message);
if (server_message instanceof Array) {
this.bindTableValues(server_message);
} else {
this.bindTableValues([server_message]);
}
} catch (e) {
this.bindTableValues(server_message);
}
// console.log('socket open');
};
socket.onclose = () => {
//console.log('Web Socket Connection Closed');
};}
async bindTableValues(server_message) {
await server_message.forEach(element => {
this.ricData = {};
let ricPeriod = '';
let itemsToUpdate = [];
let data = {};
let value = 0;
let ricData = this.ricList[element['RIC']];
if (ricData) {
if (ricData['type'] == 'swap') {
value = element['Fields']['NETCHNG_1'];
ricPeriod = ricData['disp_name'];
ricPeriod = ricPeriod.toString().trim().substring(0, ricPeriod.length - 1).toLowerCase();
if (value) {
//const itemsToUpdate: any[] = [];
this.gridApi.forEachNodeAfterFilterAndSort((rowNode) => {
if(!rowNode.group) {
data = rowNode.data;
if(data['Tenor'] == ricPeriod) {
data['LivePnL'] = parseFloat(data['DV01']) * value * 100;
itemsToUpdate.push(data);
}
}
});
// this.gridApi.applyTransaction({ update: itemsToUpdate })!;
// this.gridApi.applyTransactionAsync({ update: itemsToUpdate })!;
this.gridApi.batchUpdateRowData({ update: itemsToUpdate })!;
};
}
};
});}
ngOnDestroy(): void {
try {
//console.log('Destroy ' + this.socket.readyState);
// if (this.socket.readyState === WebSocket.OPEN) {
if (this.socket.readyState === 1) {
this.socket.close();
}
this.getRic.unsubscribe();
this.getTable.unsubscribe();
}
catch (e) {
console.log(e);
}}

How i cann loop over my array when its an observer object

i want to iterate over an array, however my array is an observer. i have tried several ways, like converting to an array. nothing works.
does anyone have a suggested solution?
i'm pretty stuck on this.
here is my code:
var vm = new Vue({
el: '#app',
data() {
return {
segmenteConfig: []
}
},
methods: {
async loadData(type) {
var url = null;
console.log("used configs -> ", this.segmenteConfig);
this.segmenteConfig.forEach(segmenteConfig => {
if (segmenteConfig.type === type) {
url = segmenteConfig.url;
console.log("used configs url -> ", url);
}
})
}
loadConfig() {
var config = [];
axios.get("ressources/segmente.json")
.then(response => {
response.data.Segmente.forEach(segmentConfig => {
this.segmenteConfig.push(segmentConfig);
});
});
}
},
created() {
this.loadConfig();
this.loadData('internet');
}
});

How to append a JSON to another JSON

I am trying to append the new object in the for loop to the request JSON.
this is not working :
setCapabilities('default',['1','2','3'])
export function
setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]){
var request:object = {
type:'setCapabilities',
kaiId:kaiId
};
capabilitiesArr.forEach(element => {
var obj = {
element:true
}
console.log(obj)
});
}
This is also not working :
export function setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]){
var request:object = {
type:'setCapabilities',
kaiId:kaiId
};
capabilitiesArr.forEach(element => {
var obj[element]=true
console.log(obj)
});
}
I want the output to be as :
console.log(request)
{
type:'setCapabilities',
kaiId:'default',
'1':true,
'2':true,
'3':true
}
I've updated the code in javascript for browser to run the code snippet, but you can convert it to typescript for your use
function setCapabilities(kaiId, capabilitiesArr) {
var request = {
type: 'setCapabilities',
kaiId: kaiId
}
var obj = Object.assign({}, request)
capabilitiesArr.forEach(element => {
obj[element] = true
});
console.log(obj)
}
setCapabilities('default',['1','2','3'])
In typescript use below code
function setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]) {
var request:object = {
type: 'setCapabilities',
kaiId: kaiId
}
var obj = {...request}
capabilitiesArr.forEach(element => {
obj[element] = true
});
console.log(obj)
}

Can't compare MongoDB data with javascript array

I want to compare the data which I got from Mongo to javascript array. I am using lodash to compare. But it always return incorrect result.
var editUser = function(userData, getOutFunction) {
var status = CONSTANTS.NG;
checkExistUser(userData._id).then(function(user) {
if (user !== null) {
var userGroup = JSON.stringify(user.group);
user.group = user.group.map((groupId) => {
return groupId.toString();
});
var removedGroups = _.difference(userGroup, userData.group);
var addedGroups = _.difference(userData.group, userGroup);
console.log('Removed Groups: ', removedGroups);
console.log('Added Groups: ', addedGroups);
} else {
status = CONSTANTS.NG;
logger.debug(DEBUG_CLASS_NAME, "Cannot find object");
if (typeof(getOutFunction) !== 'undefined') {
getOutFunction(status, null);
} else {
NO_CALLBACK();
}
}
}).catch(function() {
console.log('Promise is error');
});
var checkExistUser = function(userId) {
return new Promise(function(resolve, reject) {
UserDAO.findById(userId, function(err, user) {
if (err) {
logger.debug(DEBUG_CLASS_NAME, {
name: err.name,
code: err.code,
message: err.message,
method: "checkExist"
});
resolve(null);
} else {
resolve(user);
}
});
});
}
For example:When I try to input value for lodash difference function
var user.group = ["58b8da67d585113517fed34e","58b8da6ed585113517fed34f"];
var userData.group = [ '58b8da67d585113517fed34e' ];
I want lodash difference return below result:
Removed Groups: ['58b8da6ed585113517fed34f']
Added Groups: []
However, the function gave me the result like:
Removed Groups: []
Added Groups: [ '58b8da67d585113517fed34e' ]
Can anyone help me in this case?
I will do appreciate it.
I have had this issue as well, the result from mongodb is an ObjectId type so you can compare the someObjectId.toString() value with your array of strings, or you could use
someObjectId.equals(stringOrObjectIdValue)
However, if you want to keep using lodash functions you will either have to force both arrays to strings or to ObjectIds before passing them into the function.

nightmare how to looply select the selector

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });
var fs = require('fs');
var result;
nightmare
.goto('http://football-system.jp/fss/pub_penaltylist.php?lid=eBVesRz5C54=')
.wait('select[name="selectTeam"]')
.evaluate(function () {
var options = document.querySelectorAll('option'),i;
var values =[]
for (i = 1; i < options.length; ++i) {
values.push(options[i].value)
}
return values;
})
.then(function (values) {
console.log(values)
values.reduce(function(accumulator, value) {
return accumulator.then(function(results) {
return nightmare.goto("http://football-system.jp/fss/pub_penaltylist.php?lid=eBVesRz5C54=")
.wait('select[name="selectTeam"]')
.select('select[name="selectTeam"]', value)
.wait('button[onClick="selectData();"]')
.click('button[onClick="selectData();"]')
.wait('table[class="tableOutputDate"]')
.evaluate(function () {
return document.querySelector('table[class="tableOutputDate"]').textContent;
})
.then(function(result){
console.log(result)
results.push(result);
return results;
});
});
}, Promise.resolve([])).then(function(results){
console.log(results)
});
})
.catch(function (error) {
console.error('Search failed:', error);
});
That is my code .I want to looping select all the selector in that page and get the all html data.I asked a question in here that how to loop in nightmare,but that result cant solve this problem.please help me. Thank you.
I solve my question.the problem is happened in the deal time,not in the loop logic.I add some more wait(time).I think wait(time)is better than the wait(selector).so is over. thank u attention.
var run = function * () {
//var values = ['http://www.yahoo.com', 'http://example.com', 'http://w3c.org'];
var titles = [];
for (var i = 0; i < values.length; i++) {
var title = yield nightmare.goto('.............')
//.wait('select[name="selectTeam"]')
.wait(2000)
.select('select[name="selectTeam"]', values[i])
.wait(2000)
.click('button[onClick="selectData();"]')
//.wait('table[class="tableOutputDate"]')
.wait(2000)
.evaluate(function () {
//return document.querySelector('table[class="tableOutputDate"]').textContent;
var divs = document.querySelectorAll('table[class="tableOutputDate"]'),i;
var tables = []
for (i = 0; i < divs.length; ++i) {
tables.push(divs[i].textContent)
//result += divs[i].href.toString()+"\n";
}
return tables;
})
titles.push(title);
}
return titles;
}
vo(run)(function(err, titles) {
console.dir(titles);
});

Resources