How to return a complex JSON response with Node.js?

Martin picture Martin · Jan 18, 2012 · Viewed 114.8k times · Source

Using nodejs and express, I'd like to return one or multiple objects (array) using JSON. In the code below I output one JSON object at a time. It works but this isn't exactly what I want. The response produced isn't a valid JSON response since I have many objects.

I am well aware that I could simply add all objects to an array and return that specific array in res.end. However I am afraid this could become heavy to process and memory intensive.

What is the proper way to acheive this with nodejs? Is query.each the right method to call?

app.get('/users/:email/messages/unread', function(req, res, next) {
    var query = MessageInfo
        .find({ $and: [ { 'email': req.params.email }, { 'hasBeenRead': false } ] });

    res.writeHead(200, { 'Content-Type': 'application/json' });   
    query.each(function(err, msg) {
        if (msg) { 
            res.write(JSON.stringify({ msgId: msg.fileName }));
        } else {
            res.end();
        }
    });
});

Answer

zobi8225 picture zobi8225 · Nov 22, 2012

On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName })

See the documentation