MatrixEntry1337 MatrixEntry1337 - 4 months ago 33
Node.js Question

Nodejs RangeError: Maximum call stack size exceeded, caused by sending object in response

It would be awesome if anyone can give me a helping hand with this problem.

I am currently running into a problem where calling this express route is giving me the error show below a RangeError: Maximum call stack size exceeded

It only seems to happen when I include the res.json(users[user]); function. If I substitute this function with res.send('Done'); the function runs fine.

I have tried setTimeout, setImmediate and process.nextTick, all giving me the same error, just about.

I'm sorta hoping it's a silly mistake on my end.

//Send Friend Request
router.post('/send/friend/request', auth, function(req, res, next){

var query = User.find({$or: [
{username: req.body.username},
{username: req.payload.username}
]})
.select(' username friends notifications');

query.exec(function(err, users){
if(err) return next(err);
if(users.length < 2) console.log('/send/friend/request - There was an error in accessing the users from the db');
else{

//Identify users in array
var user = users.findIndex(function(element, index){
if(element.username === req.payload.username)
return element;
});
var requestUser = (user + 1) % 2;

//addFriends
users[user].friends.push({
user: users[requestUser],
});

users[requestUser].friends.push({
user: users[user],
sent: false
});

//notifications
users[user].notifications.push({
user: users[requestUser],
type: 0,
summary: "Your friend request has been sent to " + req.body.username +".",
status: "Pending..."
});

users[requestUser].notifications.push({
user: users[user],
type: 1,
summary: "You have a new friend request from " + req.payload.username + ".",
status: "Pending..."
});

users[requestUser].save(function(err){
if(err) return next(err);
});

users[user].save(function(err){
if(err) return next(err);
});

//Here lies the culprit
res.json(users[user]);
}
});
});

Answer

Perhaps

If user contains reference by itself then res.json fail. Because req.json attempt to explode unlimited object. To avoid this problem you can:

  1. Specify user fields to send

    res.send(JSON.stringify(user, ['name', 'age', ...]))

  2. Define reference as not enumerable property

    Object.defineProperty(user, 'your-ref', {enumerable: false});

Comments