Ad

RangeError: Maximum Call Stack Size Exceeded - Cant Send MongoDB Object Via Sockets

- 1 answer

Im trying to display live data from Mongodb (Mongoose) using socket.io, but it gaves me error "Maximum call stack size exceeded"

I know that MongoDB object which is sending is large. But i dont really know how i can split him, to diplay only values.

io.on('connection', (socket) => {
    console.log("Someone connected.");

    var List1Objects1 = Post.find().limit(1).sort({_id:-1});
    socket.emit('temp', {temp: List1Objects1 })
});

Ad

Answer

First, Post.find is an async function. You'll have to use it with a promise like API or a callback:

Post.find().then(results => {
  socket.emit('temp', {temp: results});
}).catch(err => console.log(err));

And don't send the whole mongoose model through the socket:

Post.find().then(results => {
  socket.emit('temp', {temp: results.toJSON()});

  // or
  socket.emit('temp', {temp: results.toObject()});
}).catch(err => console.log(err));

There's also a lean option that you can pass while querying which converts the object to a simple object and the query is much faster:

Post.find().lean().then(results => {
  socket.emit('temp', {temp: results});
}).catch(err => console.log(err));
Ad
source: stackoverflow.com
Ad