NodeJS - Creating empty array results in array with a lot of nulls - arrays

I am creating a Node.js chat using socket.io
The problem is that when I see the console.log of history I see an array with A LOT of nulls and at the end my history entries
[null,null,null......[ { username: 'Nobody Example', message: '231', date: '03/21/2013 14:23:58' } ]]
How come these nulls are in the array?
Here is a part of my code.
var history = [];
io.sockets.on('connection', function (socket) {
socket.on('send', function (message) {
var date = time();
io.sockets.in(socket.room).emit('message', socket.username, message, date);
history[socket.room].push({ username: socket.username, message: message, date: date });
console.log(history);
});
socket.on('joinroom', function (room, username) {
socket.room = room;
socket.join(room);
if ( typeof history[room] === 'undefined' )
history[room] = [];
});
});
Edit for more details:
The problem is in the 'joinroom' event when creating the empty array for each room.
Here are few tests that I've made:
socket.on('joinroom', function (room, username) {
socket.room = room;
socket.join(room);
console.log(typeof history[room] == 'undefined');
history[room] = [];
console.log(typeof history[room] == 'undefined');
console.log(JSON.stringify(history));
});
The console logs:
true
false
[null,null,null,null,..................,null,[]]

If you have an empty array and index it with a large number (like your room id's), all slots in the array before that number are filled with undefined (which translates to null in JSON).
So try making history an object instead:
var history = {};

try below code changing to object(hash);
var history = {};
io.sockets.on('connection', function (socket) {
socket.on('send', function (message) {
var date = time();
io.sockets.in(socket.room).emit('message', socket.username, message, date);
if(history[socket.room] !== undefined) {
history[socket.room].push = { username: socket.username, message: message, date: date };
} else {
history[socket.room] = [{ username: socket.username, message: message, date: date }];
}
console.log(history);
});

Related

React multiple console.log?

Im creating a function that sends an email based on the expiry date, however, upon trial, the function works fine but the email gets sent multiple times and the console.log is shown multiple times. Does anyone know how to counteract?
if (product?.expiry) {
var arr = []
var today = new Date()
var expiry = new Date(product?.expiry)
var week = new Date(expiry.setDate(expiry.getDate() - 7))
var template = {
message: product.name + " is reaching expiry date",
footer: "Expiry Date: " + week.toDateString()
}
const interval = setInterval(() => {
if (arr.length > 0) {
clearInterval(interval)
console.log(arr)
}
if (today !== expiry) {
// actual emailing
emailjs.send(SERVICE_API, TEMPLATE_API, template, PUBLIC_API)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error)
});
arr.push('found')
}
}, 1000)
}
ALERT: I am aware that the function is sending the email when it is not the expiry date, i just want to fix up this console.log error
**rest of function: **
const expiryEmail = () => {
if (today !== week) {
emailjs.send(SERVICE_API, TEMPLATE_API, template, PUBLIC_API)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error)
});
}
}
setTimeout(() => {
})
useEffect(() => {
if (!product) {
return;
}
//problem is that the condition returns null first time around
expiryEmail()
},[])
Try to use useEffect hook instead to set interval I am sharing the code try to use that
var today = new Date()
var expiry = new Date(product?.expiry)
var week = new Date(expiry.setDate(expiry.getDate() - 7))
var template = {
message: product.name + " is reaching expiry date",
footer: "Expiry Date: " + week.toDateString()
}
useEffect(()=>{
if (today !== expiry) {
emailjs.send(SERVICE_API, TEMPLATE_API, template, PUBLIC_API)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error)
});
arr.push('found')
}
},[])
The first condition inside your setInterval method's callback, ie.
if (arr.length > 0) {
clearInterval(interval)
console.log(arr)
}
does not have a return statement, which means it will continue on to your next if block, whose condition is satisfied because you are checking is today's date is not the same as expiry 's date, which as you alerted is a conscious decision, and therefore print the console message again.
Also, I hope by multiple you mean only twice, because that is what my answer applies for, if you meant more than that, I'd like to see the part that calls this method.
Again also, you should use Mayank's suggestion and process your code inside a useEffect block, much simpler.

An empty array is returned when calling $http.get it within a service [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to get the name from an array that is being generated from $http.get, however this is returning an empty array. When i do a console it see the array populated however when i loop inside the array to get the value of name property based on whether an id is equal to a certain, the array is empty.
In my controller i have a service call that shall return the name value.
var params = { Id: $scope.Id, SettingId: $scope.SettingId };
$scope.selectedUserName = helloService.getSelectedUserName($scope.UserId, params);
In my service
I have used the getUserList function to populate the list of user in a dropdown and it works by generating the array with the values.
However When i got another page , i want to be able to display the name of the selected user, so I wanted to use the same getUserList function to retrieve the name
this.getUserList = function (val) {
var usersObj = [];
var url = "/api/v1/hello/getusers";
var params = { Id: val.Id, SettingId: val.SettingId };
var config = { params: params };
var promise = $http.get(url, config)
.then(function (response) {
angular.forEach(response.data, function (key, value) {
angular.forEach(key, function (k, index) {
usersObj[index] = ({ userId: k.userId, name: k.name});
});
});
},
function errorCallback(response) {
console.log("Unable to perform get request");
throw response;
});
var usersList = usersObj;
return usersObj;
};
this.getSelectedUserName = function (id, param) {
var name = "";
var userList =this.getUserList(param);
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
Array length is 0 but if i do a console.log(userList) before the loop , the array display the list of user data
this.getSelectedUserName = function (id, param) {
var name = "";
var userList =this.getUserList(param);
console.log(userList) ;
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
Thank you for kind responses.
Please see screenshot
This is simple Javascript, not specific to Angular. You can do
userList.forEach(user => {
if(user.userId === id) {
name = user.name;
}
});
return name;
you can try like this.
here we are using a async await.
Service
this.getUserList = function (val) {
var usersObj = [];
var url = "/api/v1/hello/getusers";
var params = { Id: val.Id, SettingId: val.SettingId };
var config = { params: params };
return new Promise((resolve, reject) => {
$http.get(url, config)
.then(function (response) {
angular.forEach(response.data, function (key, value) {
angular.forEach(key, function (k, index) {
usersObj[index] = ({ userId: k.userId, name: k.name});
});
});
},
function errorCallback(response) {
console.log("Unable to perform get request");
throw response;
});
var usersList = usersObj;
resolve(usersObj);
});
};
this.getSelectedUserName = async function (id, param) {
var name = "";
var userList = await this.getUserList(param);
console.log(userList);
angular.forEach(userList, function (value, key) {
if (value.userId == id)
name = value.name;
});
return name;
}
let me know if it is working or not.
EDIT:
If you're only trying to match one id in the array of users you don't even need to loop:
anArray = source.filter(source => source.toLowerCase().indexOf(id) === 0);
or
anObject = source.find(obj => obj.id === id);
Which Angular version is this? Your tag denotes 2.+ but you have $scope there which is ng1.x
Why can't you use ngFor in your view since you already have your arrays. You don't need to sort them in the control.
component
this.getSelectedUserName = function (id, param) {
let name = ""; // should be array if you want to add unames to it
let userList = this.getUserList(param);
// what is `angular` here? And why loop here? Use ngFor in view.
angular.forEach(userList, function (value, key) {
if (value.userId == id){
name = value.name; // will be overwritten each time
// should be name.push(value.name); // but loop in view instead
}
});
// this.users = name; // for your original sorted version
this.users = userList;
}
In your view
<li *ngFor="let user of users; index as i;>
{{user.name}}
</li>

Mongoose models' save() won't update empty array

I have an array (bookedby) in a Mongoose model defined like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BarSchema = new Schema({
date: {
type: Date,
required: true
},
barid: {
type: String,
required: true
},
bookedby: {
type: [String],
required: true
},
});
module.exports = mongoose.model('Bar', BarSchema);
I update it with following function, called by a nodejs express router:
const Bars = require("../../models/bars");
const { getToday } = require('../../utils');
module.exports = function(req, res) {
const { barid } = req.body;
const { username } = req.user;
const date = getToday();
if( !barid ) return res.json({ success: false, error: 'Please specify parameter \'barid\'.'})
Bars.findOne({ barid, date }, function (err, bar) {
if (err) return next(err);
if (!bar || bar.bookedby.indexOf(username) === -1) return res.json({ error: `Bar is not booked yet.` });
// Someone booked the bar
const index = bar.bookedby.indexOf(username);
bar.bookedby.splice(index, 1);
bar.save(err => {
if (err) res.json({ error: `Error saving booking.` });
else res.json({ success: true });
});
});
};
Everything works fine, except when I remove the last item from the bookedby array. Then the save() function doesn't update the database. The last item remains there. I guess it has something to do with mongodb optimizing empty arrays, but how can I solve this?
According to the Mongoose FAQ:
http://mongoosejs.com/docs/faq.html
For version >= 3.2.0 you should use the array.set() syntax:
doc.array.set(3, 'changed');
doc.save();
If you are running a version less than 3.2.0, you must mark the array modified before saving:
doc.array[3] = 'changed';
doc.markModified('array');
doc.save();

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.

using tedious connection,need to get the total data

hai I am new to tedious and Es-6,It may be a silly question but I am struggling,
I want the total data in a array, using tedious connections here is my code:
getZipData() {
var Connection = require('tedious').Connection;
Request = require('tedious').Request;
var config = {
userName: 'xx',
password: 'xxxx',
server: 'xxx', // You can use 'localhost\\instance' to connect to named instance
options: {
database: 'xxxxx',
rowCollectionOnDone:'true'
}
}
var connection = new Connection(config);
var jsonArray = [];
connection.on('connect', function (err) {
if (err) {
console.log(err)
}
var sql = "SELECT * FROM xxxxx";
return new Promise(function(resolve,reject){
var request = new Request(sql,
(err, rowCount, rows)=>{
if (err) {
reject(err);
}
else {
alert("rows");
console.log(rowCount + 'rows');
}
});
request.on('row', (columns)=>{
var rowObject = {};
columns.forEach((column)=> {
rowObject[column.metadata.colName] = column.value;
});
jsonArray.push(rowObject);
});
connection.execSql(request);
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
alert("jsonArray2:"+jsonArray);
resolve(jsonArray)
});
});
})
}
componentWillMount() {
this.getZipData().then(function(resolved){
console.log(resolved);
alert("data:"+resolved);
}).catch(function(rejected){
console.log(rejected);
})
}
when i add the request.on('done', function(rowCount, more) also i didn't get any data can any one give the solution for it,
I want the total data to be displayed
It looks like you're calling resolve before your query has been executed:
var jsonArray = [];
// Register callback for row event
request.on('row', (columns)=>{
var rowObject = {};
columns.forEach((column)=> {
rowObject[column.metadata.colName] = column.value;
});
jsonArray.push(rowObject);
});
// Call resolve before executing request
resolve(jsonArray);
connection.execSql(request);
The docs mention a done event that indicates a request has completed:
request.on('done', function (rowCount, more, rows) {
// Call resolve here instead?
resolve(jsonArray);
});
Disclaimer: I've haven't actually used Tedious, but from the docs linked this looks like what you're looking for.

Resources