0

I have a code like, I have a problem with sending response.

socket.on('findUserMessages', (userName) => {
    io.sockets.connected[socket.id].emit('Checking-message', {
        type: 'ss',
        text: bot,
        user: 'bot'
    });

    var dupa = db.chat.find({ user: userName }, function(err, docs) {
        userName = userName
        if (err) throw err;
        console.log('load old messages', docs)
    })

    io.emit('private message', dupa);
})

My node console output is like

[ { _id: 5888bdd6cef7952e38821f35,
text: 'O rajciu rajciu',
user: 'Adam',
time: 2017-01-25T15:01:42.733Z }]

I know that output is not a JSON string, how to solve that? I was trying to use .toArray() but without succes.

That might be silly question but I am stuck with it for a long time.

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
Piotr Kaliński
  • 227
  • 1
  • 4
  • 13
  • 1
    Possible duplicate of [How to return value from an asynchronous callback function?](http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Aᴍɪʀ Jan 27 '17 at 23:39
  • 1
    You need to emit the result inside the callback. `io.emit('private message', docs);` – Aᴍɪʀ Jan 27 '17 at 23:39
  • 1
    I don't know where to start. what does `userName = userName` do? –  Jan 27 '17 at 23:41
  • @Aᴍɪʀ this 'docs' object is not a valid JSON object, thats the main problem. – Piotr Kaliński Jan 27 '17 at 23:47
  • 1
    @PiotrKaliński `docs` is an array of objects. As long as it doesn't include a function, you can send it through the socket. what you are trying to send is not `docs`. move the `emit` after `console.log`, and replace `dupa` with `docs`. – Aᴍɪʀ Jan 27 '17 at 23:50
  • io.emit('private message', JSON.stringify(docs)); is not working, thanks a lot! – Piotr Kaliński Jan 27 '17 at 23:53
  • @PiotrKaliński you don't need to stringify it. – Aᴍɪʀ Jan 27 '17 at 23:55

1 Answers1

-2

Convert to json your result before emitting it. Try to emit JSON.stringify(dupa).

EDIT Your output is actually JSON already (JSON array), so if you want to get only JSON string on client side, convert your output to string there (JSON.strigify(result) on client side on receiving the emit event).

Arman P.
  • 4,314
  • 2
  • 29
  • 47